gpt4 book ai didi

ios - 在 Swift 中获取光标前的字符

转载 作者:搜寻专家 更新时间:2023-10-30 22:25:13 25 4
gpt4 key购买 nike

昨天我正在研究 getting and setting the cursor position in a UITextField .现在我试图获取光标位置之前的字符。所以在下面的例子中,我想返回一个“e”。

enter image description here

func characterBeforeCursor() -> String 

注释

  • 我没有看到任何其他与此相同的 SO 问题,但也许我错过了它们。

  • 我先写了这个问题,当我找到答案时,我会同时发布问题和答案。当然,欢迎更好的回答。

  • 我说的是“字符”,但 String 没问题。

最佳答案

如果光标正在显示并且其前一位的位置有效,则获取该文本。感谢this answer一些提示。

func characterBeforeCursor() -> String? {

// get the cursor position
if let cursorRange = textField.selectedTextRange {

// get the position one character before the cursor start position
if let newPosition = textField.position(from: cursorRange.start, offset: -1) {

let range = textField.textRange(from: newPosition, to: cursorRange.start)
return textField.text(in: range!)
}
}
return nil
}

enter image description here

结果

if let text = characterBeforeCursor() {
print(text)
}

根据您的示例,是“e”。

关于ios - 在 Swift 中获取光标前的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34940033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com