我正在尝试以编程方式关闭屏幕键盘,我的代码如下所示
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没有任何建议吗?
答案 0 :(得分:1)
试试这个:
// Dismiss Keyboard when user touch screen
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
让我知道它是否有效!
答案 1 :(得分:1)
将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;
}