簡體   English   中英

如何添加觀察者以改變高度?

[英]How to add an observer for a changing height?

我有一個文本區域,該區域應該具有靈活的高度,並且隨着您編寫的行數的增加而增加。

我想聽聽它的高度變化,然后在創建新行時,此監聽器會說“嗨,高度已改變!”。

初始高度

----------初始高度----------

身高變了!

----------高度已經改變! ----------

我找不到合適的方法來執行此操作,因為addObserver中的addObserver要求有一個NotificationIdentifier,例如keyboardWillShow ,在這里我沒有像heightWillChange這樣的heightWillChange

高度變化后如何調用函數?

使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM