swift_03_TextView
知识点:
1通过TextView的textViewDidChange事件捕捉当前输入内容,从而进行限制输入字数
2.通过监听IResponder.keyboardWillChangeFrameNotification事件来监视Keyboard的弹出和收起。在对应回调中,通过note.userInfo?[UIKeyboardFrameEndUserInfoKey]来拿到键盘的endFrame,从而拿到键盘的高度,对计数器进行frame操作
3.同理,通过note.userInfo?[UIKeyboardAnimationDurationUserInfoKey]拿到键盘的动画duration,进而可以通过UIView的animation动画做到同步变化计数器的frame
mport UIKit class ViewController: UIViewController,UITextViewDelegate { var limitedTextView:UITextView! var allowInputNumberLabel:UILabel! override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white self.initInputField() NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame(note:)), name:UIResponder.keyboardWillChangeFrameNotification, object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func initInputField() { limitedTextView = UITextView(frame: CGRect(x: 80, y: 80, width: self.view.frame.width - 80*2, height: 300)) self.view.addSubview(limitedTextView) limitedTextView.delegate = self limitedTextView.font = UIFont.systemFont(ofSize: 20) limitedTextView.backgroundColor = UIColor.gray allowInputNumberLabel = UILabel(frame: CGRect(x: self.view.frame.width - 50, y: self.view.frame.height - 40, width: 50, height: 40)) self.view.addSubview(allowInputNumberLabel) allowInputNumberLabel.text = "20" allowInputNumberLabel.textAlignment = .right } // todo need to limit the paste action so that the length might be exceed! func textViewDidChange(_ textView: UITextView) { let currentCharactorCount = (textView.text.count) if currentCharactorCount >= 20 { limitedTextView.resignFirstResponder() } allowInputNumberLabel.text = "\(20 - currentCharactorCount)" } @objc func keyboardWillChangeFrame(note: Notification) { let duration = note.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as! TimeInterval let endFrame = (note.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue let y = endFrame.origin.y //计算工具栏距离底部的间距 let margin = UIScreen.main.bounds.height - y UIView.animate(withDuration: duration) { // 键盘弹出 if margin > 0 { self.allowInputNumberLabel.frame.origin.y = self.allowInputNumberLabel.frame.origin.y - margin } // 键盘收起 else { self.allowInputNumberLabel.frame.origin.y = self.view.frame.height - 40 } } } }
浙公网安备 33010602011771号