【问题标题】:NSTextField Cursor PositionNSTextField 光标位置
【发布时间】:2018-12-17 04:50:51
【问题描述】:

有没有办法在NSTextField 中获取当前光标位置?我只找到对 osx 不起作用的UITextField 的答案:

if let selectedRange = textField.selectedTextRange{
  let cursorPosition = textField.offset(from: textField.beginningOfDocument,to: selectedRange.start)
}

非常感谢!

【问题讨论】:

  • 设置选中范围的方法如下:Highlight a selection in NSTextField.
  • @Willeke,谢谢!为什么你从不给出答案?
  • 因为简短的答案被低估了,在这种情况下,答案的链接不是答案。

标签: macos nstextfield nscontrol


【解决方案1】:

我正在使用这个 sn-p 来查找 NSTextField 的光标位置:

let currentEditor = textField.currentEditor() as? NSTextView
let caretLocation = currentEditor?.selectedRanges.first?.rangeValue.location // Int

【讨论】:

    【解决方案2】:
    • 方案一(通过NSViewController获取):

      let location = (viewController.view.window?.firstResponder as? NSText)?.selectedRange.location
      
    • 方案二(通过NSTextField获得):

      let location = textField.currentEditor()?.selectedRange.location
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-19
      • 2013-05-17
      相关资源
      最近更新 更多