ios 在 UITextField 中控制光标位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1500233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 16:28:46  来源:igfitidea点击:

Control cursor position in UITextField

iosiphoneuitextfielduitextpositionuitextrange

提问by Jeremy

I have a UITextFieldthat I'm forcing formatting on by modifying the text inside the change notification handler. This works great (once I solved the reentrancy issues) but leaves me with one more nagging problem. If the user moves the cursor someplace other than the end of the string then my formatting change moves it to the end of the string. This means users cannot insert more than one character at a time into the middle of the text field. Is there a way to remember and then reset the cursor position in the UITextField?

我有一个UITextField我通过修改更改通知处理程序中的文本来强制格式化。这很有效(一旦我解决了可重入问题),但又给我留下了一个烦人的问题。如果用户将光标移动到字符串末尾以外的其他位置,则我的格式更改会将其移动到字符串末尾。这意味着用户一次不能在文本字段的中间插入一个以上的字符。有没有办法记住然后重置光标位置UITextField

回答by Chris R

Controlling cursor position in a UITextField is complicated because so many abstractions are involved with input boxes and calculating positions. However, it's certainly possible. You can use the member function setSelectedTextRange:

在 UITextField 中控制光标位置很复杂,因为输入框和计算位置涉及很多抽象。然而,这当然是可能的。您可以使用成员函数setSelectedTextRange

[input setSelectedTextRange:[input textRangeFromPosition:start toPosition:end]];

Here's a function which takes a range and selects the texts in that range. If you just want to place the cursor at a certain index, just use a range with length 0:

这是一个函数,它接受一个范围并选择该范围内的文本。如果您只想将光标放在某个索引处,只需使用长度为 0 的范围:

+ (void)selectTextForInput:(UITextField *)input atRange:(NSRange)range {
    UITextPosition *start = [input positionFromPosition:[input beginningOfDocument] 
                                                 offset:range.location];
    UITextPosition *end = [input positionFromPosition:start
                                               offset:range.length];
    [input setSelectedTextRange:[input textRangeFromPosition:start toPosition:end]];
}

For example, to place the cursor at idxin the UITextField input:

例如,要将光标放在idxUITextField 中input

    [Helpers selectTextForInput:input 
                        atRange:NSMakeRange(idx, 0)];

回答by George Muntean

Useful to position at index (Swift 3)

用于定位在索引处(Swift 3)

private func setCursorPosition(input: UITextField, position: Int) {
    let position = input.position(from: input.beginningOfDocument, offset: position)!
    input.selectedTextRange = input.textRange(from: position, to: position)
}

回答by Dan J

I've finally found a solution for this problem! You can put the text you need inserted into the system pasteboard and then paste it at the current cursor position:

我终于找到了解决这个问题的方法!您可以将需要插入的文本放入系统粘贴板,然后粘贴到当前光标位置:

[myTextField paste:self]  

I found the solution on this person's blog:
http://dev.ragfield.com/2009/09/insert-text-at-current-cursor-location.html

我在这个人的博客上找到了解决方案:
http://dev.ragfield.com/2009/09/insert-text-at-current-cursor-location.html

The paste functionality is OS V3.0 specific, but I've tested it and it works fine for me with a custom keyboard.

粘贴功能是特定于 OS V3.0 的,但我已经对其进行了测试,并且使用自定义键盘可以正常工作。

If you go for this solution then you should probably save the user's existing clipboard contents and restore them immediately afterwards.

如果您采用此解决方案,那么您可能应该保存用户现有的剪贴板内容并在之后立即恢复它们。

回答by gabuchan

Here's the Swift version of @Chris R. – updated for Swift3

这是@Chris R. 的 Swift 版本——已针对 Swift3 更新

private func selectTextForInput(input: UITextField, range: NSRange) {
    let start: UITextPosition = input.position(from: input.beginningOfDocument, offset: range.location)!
    let end: UITextPosition = input.position(from: start, offset: range.length)!
    input.selectedTextRange = input.textRange(from: start, to: end)
}

回答by Pavel Alexeev

Feel free to use this UITextFieldcategory to get and set cursor position:

随意使用这个UITextField类别来获取和设置光标位置:

@interface UITextField (CursorPosition)

@property (nonatomic) NSInteger cursorPosition;

@end

——

@implementation UITextField (CursorPosition)

- (NSInteger)cursorPosition
{
    UITextRange *selectedRange = self.selectedTextRange;
    UITextPosition *textPosition = selectedRange.start;
    return [self offsetFromPosition:self.beginningOfDocument toPosition:textPosition];
}

- (void)setCursorPosition:(NSInteger)position
{
    UITextPosition *textPosition = [self positionFromPosition:self.beginningOfDocument offset:position];
    [self setSelectedTextRange:[self textRangeFromPosition:textPosition toPosition:textPosition]];
}

@end

回答by pix0r

I don't think there is a way to place the cursor at a particular place in your UITextField(unless you got very tricky and simulated a touch event). Instead, I'd handle formatting when the user has finishedediting their text (in textFieldShouldEndEditing:) and if their entry is incorrect, don't allow the text field to finish editing.

我认为没有办法将光标放置在您的特定位置UITextField(除非您非常棘手并模拟了触摸事件)。相反,我会在用户完成编辑文本(在textFieldShouldEndEditing:)时处理格式,如果他们的输入不正确,则不允许文本字段完成编辑。

回答by Alex Cio

Here is a snippet which works fine for this problem:

这是一个可以很好地解决这个问题的片段:

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    UITextPosition *positionBeginning = [textField beginningOfDocument];
    UITextRange *textRange =[textField textRangeFromPosition:positionBeginning 
                                                  toPosition:positionBeginning];
    [textField setSelectedTextRange:textRange];
}

Source from @omz

来自@omz