这是我在这个论坛上的第一个问题。我想知道如何仅在 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/