【问题标题】:Can't dismiss keyboard for iPhone 5 and iPhone5s无法关闭 iPhone 5 和 iPhone 5s 的键盘
【发布时间】:2016-01-21 13:20:59
【问题描述】:

我正在尝试以编程方式关闭屏幕键盘,我的代码如下

override func viewDidLoad() {
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil);
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil);
}

func keyboardWillShow(notification: NSNotification) {
    var info = notification.userInfo!
    let keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
    UIView.animateWithDuration(0.1, animations: { () -> Void in
        self.Bottomspace.constant = keyboardFrame.size.height
    })
}

func keyboardWillHide(notification: NSNotification){
    self.Bottomspace.constant = 0
}

它适用于 iPhone 6 和 iPad,但不适用于 iPhone 5 和 iPhone 5s,有什么建议吗?

【问题讨论】:

  • 就在你点击 UITextField 之外的时候?
  • 不,我点击键盘上的返回键

标签: ios swift keyboard


【解决方案1】:

试试这个:

 // Dismiss Keyboard when user touch screen
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        self.view.endEditing(true)
    }

让我知道它是否有效!

【讨论】:

    【解决方案2】:

    将 UITextFieldDelegate 添加到类声明中:

    class ViewController: UIViewController, UITextFieldDelegate
    

    连接文本字段或以编程方式编写

    @IBOutlet weak var userText: UITextField!
    

    将您的视图控制器设置为视图中的文本字段委托已加载:

    override func viewDidLoad() {
    super.viewDidLoad()
    self.userText.delegate = self
    }
    

    添加此委托

    func textFieldShouldReturn(userText: UITextField!) -> Bool {
    yourtextfield.resignFirstResponder()
    return true;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-28
      • 1970-01-01
      • 1970-01-01
      • 2014-04-07
      • 1970-01-01
      • 2015-02-22
      • 2011-03-21
      • 1970-01-01
      相关资源
      最近更新 更多