NSTextView监视器插入位置更改

时间:2015-08-13 10:38:49

标签: macos cocoa key-value-observing nstextfield nstextview

如何在NSTextView的插入位置更改中获得回调?

我试过KVO

[textView addObserver:self forKeyPath:@"selectedRange" options:NSKeyValueObservingOptionNew context:NULL];

但是当我使用箭头键或鼠标移动时,我不会得到回调...可能是因为范围是一个结构,它会修改其成员(我只在文本发生变化时才回调)

但是如何监控插入位置变化?

2 个答案:

答案 0 :(得分:1)

使用- (void)textViewDidChangeSelection:(NSNotification *)aNotification

答案 1 :(得分:0)

Swift 4版本:

public func textViewDidChangeSelection(_ notification: Notification) {
   guard let textView = notification.object as? NSTextView,
         let string = textView.textStorage?.string else {
      return
   }

   if let nsRange = textView.selectedRanges.first as? NSRange,
      let range = Range(nsRange, in: string) {
      print(nsRange)
      print(range.lowerBound.encodedOffset, range.upperBound.encodedOffset)
   }
}
相关问题