漏洞?由UITextFieldDelegate进行的UILabel实时更新关闭了一个字符 [英] Bug? UILabel live updating by UITextFieldDelegate is off by one character

查看:86
本文介绍了漏洞?由UITextFieldDelegate进行的UILabel实时更新关闭了一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个示例应用程序,用于演示我遇到的问题:

Here is a sample app to demonstrate the issue that I ran into:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var aTextField: UITextField!
    @IBOutlet weak var aTextLbl: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        aTextField.delegate = self
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        aTextLbl.text = aTextField.text
        return true
    }
}

这是一个演示:

链接到Gif动画

我的问题是,如何使标签与我在文本字段中键入的内容完全同步?谢谢!

My question is, how to make it such that the label is exactly synced with what I type in the textfield? Thanks!

推荐答案

可以使用EditingChanged而不是使用委托方法shouldChangeCharactersIn

Rather than using delegate method shouldChangeCharactersIn, you can use EditingChanged as follows.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var aTextLbl: UILabel!
    @IBOutlet weak var aTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func editingChanged(_ sender: UITextField) {
        aTextLbl.text = aTextField.text
    }
}

这篇关于漏洞?由UITextFieldDelegate进行的UILabel实时更新关闭了一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆