如何为高度变化添加观察者?

时间:2016-06-27 15:16:17

标签: ios swift uitextfield

我有一个文本区域,它应该具有灵活的高度,沿着你编写的行数增长。

我想听听它的高度变化,然后当创建一个新线时,这个听众会说“嗨高度已经改变了!”。

Initial Height

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

Height has changed !

----------身高已经改变!!! ----------

我找不到合适的方法来执行此操作,因为swift中的addObserver需要像keyboardWillShow这样的NotificationIdentifier,而这里我没有像heightWillChange那样的人。

高度变化后如何调用函数?

3 个答案:

答案 0 :(得分:1)

使用UITextView

的委托方法
var textViewHeight: CGFloat = 0

func textViewDidChange(textView: UITextView)
{
    let newTextViewHeight = textView.frame.size.height
    if textViewHeight != newTextViewHeight
    {
        print("---------- Height has changed !!! ----------")
    }
    textViewHeight = newTextViewHeight
}

答案 1 :(得分:0)

您可以使用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")
}

答案 2 :(得分:0)

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
    }
}
相关问题