[英]How to add an observer for a changing height?
使用UITextView
委托方法
var textViewHeight: CGFloat = 0
func textViewDidChange(textView: UITextView)
{
let newTextViewHeight = textView.frame.size.height
if textViewHeight != newTextViewHeight
{
print("---------- Height has changed !!! ----------")
}
textViewHeight = newTextViewHeight
}
您可以使用KVO。 如果從視圖控制器執行此操作,則可以在viewDidLoad
添加觀察。 例如:
override func viewDidLoad() {
super.viewDidLoad()
self.textField = UITextField(frame: CGRect(x: 0.0, y: 0.0, width: 100.0, height: 100.0))
self.textField.addObserver(self, forKeyPath: "frame", options: .New, context: nil)
}
然后回應:
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath == "frame" && object === self.textField
{
print(self.textField.frame)
}
}
然后在取消初始化視圖控制器時刪除觀察:
deinit {
self.textField.removeObserver(self, forKeyPath: "frame")
}
extension MyThing: UITextViewDelegate {
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
guard let oldText = textView.text else {
return true
}
let newText = (textView.text as NSString).replacingCharacters(in: range, with: text)
let size = CGSize(width: textView.bounds.width, height: CGFloat.greatestFiniteMagnitude)
let font = textView.font!
let oldTextRect = newText.boundingRect(with: size,
options: .usesLineFragmentOrigin,
attributes: [.font : font],
context: nil)
let newTextRect = oldText.boundingRect(with: size,
options: .usesLineFragmentOrigin,
attributes: [.font : font],
context: nil)
if oldTextRect != newTextRect {
print("Text height changed")
} else {
print("Text height didnt change :(")
}
return true
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.