ios - 在不让光标移动到末尾的情况下格式化 UITextField 文本

标签 ios swift uitextfield uitextfielddelegate

在处理一个新的文本条目后,我试图将 NSAttributedString 样式应用到 UITextField,逐个按键。问题是每当我替换文本时,光标都会在每次更改时跳到最后。这是我目前的方法……

立即接收并显示文本更改(同样的问题适用于我返回 false 并手动进行文本替换)

func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {        
    let range:NSRange = NSRange(location: range.location, length: range.length)
    let newString = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string);
    return true
}

我订阅了 UITextFieldTextDidChangeNotification 通知。这会触发样式。更改文本后,我使用一些 format() 函数将其 (NSString) 替换为格式化版本 (NSAttributedString)。

func textFieldTextDidChangeNotification(userInfo:NSDictionary) {
    var attributedString:NSMutableAttributedString = NSMutableAttributedString(string: fullString)
    attributedString = format(textField.text) as NSMutableAttributedString
    textField.attributedText = attributedString
}

这样的样式效果很好。但是,每次替换文本后,光标都会跳到字符串的末尾。如何关闭此行为或手动将光标移回开始编辑的位置? ……或者是否有更好的解决方案来在编辑时设置文本样式?

最佳答案

实现这一点的方法是抓取光标的位置,更新字段内容,然后将光标放回原来的位置。我不确定 Swift 中的确切等价物,但以下是我在 Obj-C 中的做法。

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    UITextPosition *beginning = textField.beginningOfDocument;
    UITextPosition *cursorLocation = [textField positionFromPosition:beginning offset:(range.location + string.length)];

    textField.text = [textField.text stringByReplacingCharactersInRange:range withString:string];

    /* MAKE YOUR CHANGES TO THE FIELD CONTENTS AS NEEDED HERE */

    // cursorLocation will be (null) if you're inputting text at the end of the string
    // if already at the end, no need to change location as it will default to end anyway
    if(cursorLocation)
    {
        // set start/end location to same spot so that nothing is highlighted
        [textField setSelectedTextRange:[textField textRangeFromPosition:cursorLocation toPosition:cursorLocation]];
    }

    return NO;
}

关于ios - 在不让光标移动到末尾的情况下格式化 UITextField 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26284271/

相关文章:

iphone - 加载 uiview 后更改 uilabel 文本

ios - 如何访问我项目的资源文件夹中所有文件的列表?

ios - 如何使用图标向 UITextField 添加填充

iOS swift : Cannot Manipulate String: Value of type 'String' has no member 'firstIndex'

ios - ios编辑文本字段无限循环

iOS 11.0 UITextField secureTextEntry 不起作用?

iphone - UISegmentedControl 放在 tableView 标题中时行为异常

ios Firebase - 在 "details post" Controller 中继续数据

ios - 如何在具有匹配键值的 NSArray 中找到字典索引 - Swift

ios - CollectionView estimatedItemSize 未按预期工作