ios - 检查 TextField 不为空后如何启用 UIBarItem

标签 ios swift3

这是我在这个论坛上的第一个问题。我想知道如何仅在 UITextField 中包含文本时启用 UIBarButtonItem。我已经看到很多关于如何在 Swift 2 但不是 Swift 3 中执行此操作的示例。这是一个简单的应用程序,用于将一些数据保存到核心数据。除了 UIOutlets 等,我没有任何代码可以显示,因为我不确定如何动态检查 UITextField 中的文本。

最佳答案

这就是为什么我不建议使用 Interface Builder 和 Storyboards,开发人员会被“愚弄”。

无论如何,算法是这样的:

1) 文本字段具有用于文本字段事件(例如用户点击返回/完成键)的回调方法或“委托(delegate)”方法。

所以首先,您需要告诉您的文本字段委托(delegate)是您的 View Controller 。

2) 您定义必要的 UITextField 委托(delegate)方法 ( https://developer.apple.com/reference/uikit/uitextfielddelegate )

3) UITextField 有一个 hasText 方法(新适用于 iOS 10+)来判断您的文本字段是否有任何文本。如果有,则启用栏按钮项,否则禁用它。

您也可以使用 if let 可选绑定(bind)来解包 textField.text? 属性,然后检查 text.characters.count 是否大于 0,如下所示:

if let text = textField.text {
    navigationItem.rightBarButtonItem?.isEnabled = text.characters.count > 0
}

这是传统的做法(在 iOS 10 之前,如果你想支持旧版 iOS 版本):D

完整代码如下:

class ViewController: UIViewController, UITextFieldDelegate {
    @IBOutlet var myTextField:UITextField!

    ...

    override func viewDidLoad() {
        super.viewDidLoad()

        // self is referring to this view controller
        ...
        myTextField.returnKeyType = UIReturnKeyType.done
        myTextField.delegate = self
    }

    // UITextField Delegate Methods
    func textFieldDidEndEditing(_ textField: UITextField) {

        // get the navigation bar button (right bar button in my case)
        // and set its "isEnabled" property depending on whether
        // the textField has any text using "hasText" of UITextField
        navigationItem.rightBarButtonItem?.isEnabled = textField.hasText
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {

        hideKeybaord()

        return false
    }

    // UITouches delegate methods for extra user experience polish
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        // hides keyboard when user taps on the background
        hideKeybaord()
    }

    // resusable hideKeyboard method
    func hideKeybaord() {
        myTextField.resignFirstResponder()

        // in case you need to hide all other text fields in the future
        // textField2.resignFirstResponder()
        // textField3.resignFirstResponder()
    }
}

关于ios - 检查 TextField 不为空后如何启用 UIBarItem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40106574/

相关文章:

ios - Swift:异步数据任务永远不会终止

ios - swift 中的 xcode 6 beta EXC_BREAKPOINT(代码=EXC_I386_BPT,子代码=0x0)

swift - Completion 很快就会被调用

ios - Interface Builder 文件中的未知类 _TtC8<appName>20MasterViewController

ios - 如果在 viewDidLoad 中将 Alpha 设置为 0 然后淡入,则 UISlider 不会被选中

ios - Swift 获取前几年的日期时间 GMT+08 :00 timezone

ios - 错误域 = com.apple.healthkit = 3 "Workout Session is Not Current"错误?

swift - 非 -'@objc' 方法不满足 '@objc' 协议(protocol)的可选要求

swift - Realm 模型类文件

ios - 选择器 View Swift