首页 > 解决方案 > Is there a way to hide a UILabel when the user starts typing, and then make it re-appear if the user removes all input?

问题描述

I'm trying to implement a search field where you type in some characters to show "possible searches". In the beginning there is a small text underneath the textbox that says "make sure to capitalize letters". This is just a UILabel. I want to make this label "disappear" when the user STARTS to type. But if the user backspaces enough to remove all text - I want the label to re-appear again.

The textbox is just made from UITextField.

This is all stored in a view.

Does anyone have an idea of how to implement something like this?

标签: iosuitextfielduilabel

解决方案


您可以使用像这样的选择器将目标添加到您的 textFiled 来做到这一点

  1. 将此目标添加到您的viewDidLoad方法中
yourTextFiled.addTarget(self, action: #selector(self.textFieldDidChange(_:)), for: UIControl.Event.editingChanged)
  1. 在您的方法下方创建像这样的选择器方法viewDidLoad并设置是否 textfield.text.isEmpty 比标签像这样隐藏
    @objc func textFieldDidChange(_ textField: UITextField) {
        if textField.text!.isEmpty {
            label.isHidden = false
        } else {
            label.isHidden = true
        }
    }

希望你得到你想要的东西!


推荐阅读