如何获取UITextField游标更改事件?

时间:2016-09-01 09:58:52

标签: ios events cursor uitextfield

我正在使用Android TV遥控器 - iOS版

我需要在UITextField中检测光标更改事件,并将此事件发送到Android TV。

我找不到任何委托或通知会发送UITextfield游标更改事件。

有什么方法可以举办此活动吗?

非常感谢。

2 个答案:

答案 0 :(得分:0)

观察selectedTextRange属性。

关于RxSwift的例子:

textField.rx.observeWeakly(UITextRange.self, "selectedTextRange")
            .observeOn(MainScheduler.asyncInstance)
            .skip(1)
            .bind { (newTextRange) in
                print(newTextRange)
            }
            .disposed(by: disposeBag)

答案 1 :(得分:0)

据我所知,您可以KVO或子类。 由于@NSLeader给出了KVO的答案,因此我将解释后者。

这是一个子类示例:

class MyUITextFieldThatEmitsCursorChangeEvents: UITextField
{
    //Override this, but don't prevent change to its default behavior by 
    //calling the super getter and setter.
    override var selectedTextRange: UITextRange? {
        get {return super.selectedTextRange}
        set {
            emitNewlySetCursor(event: newValue) //<- Intercept the value
            super.selectedTextRange = newValue
        }
    }
    //I'm going to use a closure to pass the cursor position out, 
    //but you can use a protocol, NotificationCenter, or whatever floats your
    //boat.
    var cursorPosnDidChangeEvent: ((Int) -> ())?

    //I'm going to abstract the logic here to keep the previous code slim.
    private func emitNewlySetCursor(event range: UITextRange?)
    {
        //Now you have access to the start and end in range.
        //If .start and .end are different, then it means text is highlighted.
        //If you only care about the position where text is about to be 
        //entered, then only worry about .start.
        //This is an example to calculate the cursor position.
        if let rawRangeComponent = range?.start 
        {
            let cursorPosition = offset(from: beginningOfDocument, 
                                        to: rawRangeComponent)

            //Emit the value to whoever cares about it
            cursorPosnDidChangeEvent?(cursorPosition) 
        }
    }
}

然后,例如,如果我们在U​​IViewController中:

override func viewDidLoad() 
{
    super.viewDidLoad()

    let tf = MyUITextFieldThatEmitsCursorChangeEvents(frame: .zero)
    view.addSubview(tf)
    tf.cursorPosnDidChangeEvent = { newCursorPosn in
        print(newCursorPosn) //( ͡° ͜ʖ ͡°)
    }
}