问题
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