2016-01-21 46 views
0
关闭键盘

我试图编程方式关闭屏幕上的键盘和我有我的代码如下无法为iPhone 5和iPhone5s

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

就在您点击UITextField外部时? – senty

+0

诺普,我做键盘上的返回键 –

回答

1

试试这个:

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

让我知道,如果它的工作原理!

+0

啊,它的工作原理!非常感谢你! –

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; 
}