我有一个textView使用textView shouldChangeTextIn函数仅允许一定数量的字符,我也有一个将按钮绑定到键盘的函数,问题是当我使用shouldChangeTextIn范围函数将键盘解除绑定时,如何我可以解决这个问题吗?我在viewDidLoad中调用bindToKeyboard
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
self.amountLabel.isHidden = false
var amount = 0
var count = self.textView.text?.count
amount = 280 - count!
self.amountLabel.text = String(amount)
if(amount <= 0){
self.textView.text?.remove(at: (self.textView.text?.index(before: (self.textView.text?.endIndex)!))!)
}
return true
}
extension UIView {
func bindToKeyboard(){
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(_:)), name: NSNotification.Name.UIKeyboardDidChangeFrame, object: nil)
}
@objc func keyboardWillChange(_ notification: NSNotification){
let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
let curve = notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! UInt
let beginningFrame = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
let endFrame = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let deltaY = endFrame.origin.y - beginningFrame.origin.y
UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIViewKeyframeAnimationOptions(rawValue: curve), animations: {
self.frame.origin.y += deltaY
}, completion: nil)
}
}