swift 输入框随键盘移动

前端之家收集整理的这篇文章主要介绍了swift 输入框随键盘移动前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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字够多了哦")
        }
    }

猜你在找的Swift相关文章