【问题标题】:How to show entered data from UITextField to Label permanently?如何永久显示从 UITextField 输入的数据到标签?
【发布时间】:2018-03-01 07:49:06
【问题描述】:

我正在尝试创建一个功能,当用户在 UITextField 中输入文本时,标签显示输入的文本。

我怎样才能做到?

喜欢:


textField.text = "10"

Label.text = "\(textField.text) smthg" //. (10 smthg)

textField.text = "10.56"

Label.text = "\(textField.text) smthg" //. (10.56 smthg)

【问题讨论】:

  • 您可以在此文本字段委托方法func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {}中更新标签

标签: ios swift uitextfield uilabel func


【解决方案1】:

实现UITextFieldDelegate 并将其设置为textField.delegate 属性。从UITextFieldDelegate 实现shouldChangeCharactersIn 回调方法,每次用户尝试更改文本字段中的输入时都会调用该方法:

class MyViewController: UIViewController {

    ...

    func viewDidLoad() {
        super.viewDidLoad()

        // set the textField's delegate to self
        textField.delegate = self
    }

}

extension MyViewController: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        // to be always updated, you cannot use textField.text directly, because after this method gets called, the textField.text will be changed
        let newStringInTextField = (textField.text as NSString?)?.replacingCharacters(in: range, with: string)
        yourLabel.text = "\(newStringInTextField) smthg"
        return true
    }
}

使用函数的参数,您可以获得一个将出现在textField 中的字符串,您可以将其设置为yourLabel 中的文本。

【讨论】:

    【解决方案2】:

    你需要实现textfield的委托方法shouldChangeCharactersIn,当用户开始输入时会调用它,从文本域中删除一个字符,当文本域中有文本时,单击文本域右侧出现的清除按钮。

    【讨论】:

      【解决方案3】:

      您可以使用Editing Changed Action 来实现textField

      @IBAction func changeText(_ sender: UITextField) {
      
           Label.text = "\(textField.text) smthg"
      }
      

      【讨论】:

        猜你喜欢
        • 2019-11-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-07
        • 2011-08-01
        • 2017-07-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多