好吧,在尝试了很多方法来解决这个问题之后,我决定只使用以下方法UITextView
来代替UITextField
as :UITextFieldDelegate
- (void)textViewDidChangeSelection:(UITextView *)textView
因为我希望我的标记在我的 中脱颖而出UITextView
,所以我决定使用NSAttributedString
突出显示我的文本。由于标记现在具有与普通文本不同的属性,因此我可以使用以下内容检查所选文本是否为标记:
- (id)attribute:(NSString *)attributeName atIndex:(NSUInteger)index effectiveRange:(NSRangePointer)aRange
我写了一个方法,它将接受任何UITextPosition
给定的UITextView
并以 a 的形式返回标记的最近左开始NSInteger
。这样我就可以轻松地使用它来制作NSRange
:
- (NSInteger)textViewWrappedIntegerFromPosition:(UITextPosition *)position forTextField:(UITextView *)textView
{
NSInteger integer = [textView offsetFromPosition:textView.beginningOfDocument toPosition:position];
NSInteger newInteger = integer;
UIColor *color = [textView.attributedText attribute:NSForegroundColorAttributeName atIndex:integer-1 effectiveRange:NULL];
// left of it is a character from a token
if ([[UIColor colorWithRed:0.5 green:0.5 blue:1.0 alpha:1.0] isEqual:color])
{
NSInteger newInteger = integer+1;
UITextPosition *startMinus = [textView positionFromPosition:position offset:-1];
NSInteger startMinusInt = [textView offsetFromPosition:textView.beginningOfDocument toPosition:startMinus];
UIColor *colorMinus = [textView.attributedText attribute:NSForegroundColorAttributeName atIndex:startMinusInt effectiveRange:NULL];
// left and right of it is a character from a token
if ([[UIColor colorWithRed:0.5 green:0.5 blue:1.0 alpha:1.0] isEqual:colorMinus]) // both collision
{
while ([colorMinus isEqual:[UIColor colorWithRed:0.5 green:0.5 blue:1.0 alpha:1.0]] && startMinusInt > 0)
{
// I used offset -1 again because when I wrote this I was testing something else
position = [textView positionFromPosition:position offset:-1];
startMinusInt = [textView offsetFromPosition:textView.beginningOfDocument toPosition:position];
colorMinus = [textView.attributedText attribute:NSForegroundColorAttributeName atIndex:startMinusInt effectiveRange:NULL];
}
if (startMinusInt != 0)
{
newInteger = startMinusInt+1;
}
else
{
newInteger = startMinusInt;
}
return newInteger;
}
return newInteger;
}
return newInteger;
}
使用此方法,我可以计算选择的start
andend
UITextPosition
是否在标记中或与标记相邻,然后我可以继续创建新范围并将其设置为新选择:
[textView setSelectedRange:NSRangeMake(newStartInt,newEndInt-newStartInt];