1

用于为我的字符串NSMutableAttributedString着色UITextField,但随后用户无法剪切、复制或删除字符串。例如,使用下面的代码,如果我输入“blue red @green”,然后尝试删除蓝色或剪掉蓝色,当我尝试光标移动到UITextfield?中的最后一个字母时

有什么建议么?

- (void)colorText {
NSMutableAttributedString * string = [[NSMutableAttributedString alloc]initWithString:self.thing.text];

NSArray *words=[self.thing.text componentsSeparatedByString:@" "];

for (NSString *word in words) {
    if([word isEqualToString:@""]) {continue;};
    if ([word hasPrefix:@"@"]) {
        NSRange range=[self.thing.text rangeOfString:word];
        [string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:range];
    } else {
        NSRange range=[self.thing.text rangeOfString:word];
        [string addAttribute:NSForegroundColorAttributeName value:[UIColor darkGrayColor] range:range];
    }
}
[self.thing setAttributedText:string];
}
4

1 回答 1

1

问题是您每次都在设置字符串的文本,这会擦除当前字符串并放入一个新字符串,这会将光标移动到末尾并覆盖您将对原始字符串进行的任何编辑。您可以自己进行编辑,调用colorText然后 return NO,这将进行编辑,但您仍然会遇到光标问题。

解决方案是获取光标的范围,手动进行编辑,调用colorText,将光标放回它应该在的位置,然后返回NO。我知道这听起来很复杂,但代码还不错。

- (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];

    [textField colorText]; // or however you call this on your field

    // 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;
}
于 2014-07-17T16:11:47.817 回答