step 1:
//监听键盘改变 NSNotificationCenter.defaultCenter().addobserver(self,selector:#selector(CommentDetailViewController.keyboardWillChange(_:)),name:UIKeyboardWillChangeFrameNotification,object: nil)
step 2:
实现监听方法
func keyboardWillChange(note:NSNotification){ let duration:Double = (note.userInfo![UIKeyboardAnimationDurationUserInfoKey]?.doubleValue)! let keyboardY:CGFloat = (note.userInfo![UIKeyboardFrameEndUserInfoKey]?.CGRectValue().origin.y)! let ty = keyboardY - SCREEN_HEIGHT UIView.animateWithDuration(duration) { self.fieldBar?.transform = CGAffineTransformMakeTranslation(0,ty) } } // 移除监听 deinit{ NSNotificationCenter.defaultCenter().removeObserver(self) }
另:限制输入框字数
实现 UITextFieldDelegate 方法
func textFieldDidChange(textField:UITextField){ let cleanString = textField.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) if(Nsstring(string: textField.text!).length > 150){ textField.text = Nsstring(string: cleanString).substringToIndex(150) Util.showMessage("150字够多了哦") } }