加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift 输入框随键盘移动

发布时间:2020-12-14 06:40:59 所属栏目:百科 来源:网络整理
导读:step 1: //监听键盘改变 NSNotificationCenter.defaultCenter().addObserver(self,selector:#selector(CommentDetailViewController.keyboardWillChange(_:)),name:UIKeyboardWillChangeFrameNotification,object: nil) step 2: 实现监听方法 func keyboardW

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读