Get character before cursor in Swift

雨燕双飞 提交于 2020-01-03 15:15:46

问题


Yesterday I was working on getting and setting the cursor position in a UITextField. Now I am trying to get the character just before the cursor position. So in the following example, I would want to return an "e".

func characterBeforeCursor() -> String 

Notes

  • I didn't see any other SO questions that were the same of this, but maybe I missed them.

  • I wrote this question first and when I find an answer I will post both the question and the answer at the same time. Of course, better answers are welcomed.

  • I said "character" but String is fine.


回答1:


If the cursor is showing and the position one place before it is valid, then get that text. Thanks to this answer for some hints.

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
}

The result of

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

is "e", as per your example.




回答2:


You can also use this:

NSInteger endOffset = [textfld offsetFromPosition:textfld.beginningOfDocument toPosition:range1.end];

NSRange offsetRange = NSMakeRange(endOffset-1, 1);

NSString *str1 = [textfld.text substringWithRange:offsetRange];
NSLog(@"str1= %@",str1);



回答3:


In swift you can use

let range1 : UITextRange = textField.selectedTextRange!

let  endoffset : NSInteger = textField.offsetFromPosition(textField.beginningOfDocument, toPosition: range1.end)

let offsetRange : NSRange = NSMakeRange(endoffset-1, 1)

let index: String.Index = (textField.text?.startIndex.advancedBy(offsetRange.location))!

let str1 : String = (textField.text?.substringFromIndex(index))!

let index1 : String.Index = str1.startIndex.advancedBy(1)

let str2: String = str1.substringToIndex(index1)

print(str2)


来源:https://stackoverflow.com/questions/34940033/get-character-before-cursor-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!