【问题标题】:How to add target to keyboard done/go/search buttons?如何将目标添加到键盘完成/开始/搜索按钮?
【发布时间】:2018-05-21 07:47:27
【问题描述】:

我想在键盘上的按钮上附加一个动作。我不想创建自定义键盘,只处理搜索/执行/完成按钮操作。

谢谢!

【问题讨论】:

    标签: ios swift keyboard action addtarget


    【解决方案1】:

    要处理返回密钥,请使用委托textFieldShouldReturn

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
             // your Action According to your textfield
            return true
        }
    

    如何更改返回键

    yourTextField.returnKeyType = UIReturnKeyType.search
    yourTextField.returnKeyType = UIReturnKeyType.done
    

    苹果枚举:

    typedef NS_ENUM(NSInteger, UIReturnKeyType) {
        UIReturnKeyDefault,
        UIReturnKeyGo,
        UIReturnKeyGoogle,
        UIReturnKeyJoin,
        UIReturnKeyNext,
        UIReturnKeyRoute,
        UIReturnKeySearch,
        UIReturnKeySend,
        UIReturnKeyYahoo,
        UIReturnKeyDone,
        UIReturnKeyEmergencyCall,
        UIReturnKeyContinue NS_ENUM_AVAILABLE_IOS(9_0),
    }
    

    【讨论】:

      【解决方案2】:

      实现UITextFieldDelegate 方法textFieldShouldReturn 以获取该按钮被点击的事件,而与按钮的名称无关。

      class YourViewController: UIViewController, UITextFieldDelegate {
          //conform protocol of `UITextFieldDelegate` in any of `viewDidLoad` or `viewWillAppear` method
          self.textFieldYouWantToHandle.delegate = self;
      
          func textFieldShouldReturn(_ textField: UITextField) -> Bool {
              if textField == textFieldYouWantToHandle {
                 //any task to perform
                 textField.resignFirstResponder() //if you want to dismiss your keyboard
              }
              return true
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-05-20
        • 2012-04-22
        • 1970-01-01
        • 2012-02-23
        • 1970-01-01
        • 2016-01-08
        • 1970-01-01
        相关资源
        最近更新 更多