さて、これを回避するためにたくさんの方法を試した後、 asUITextView
の代わりに次の方法を使用することにしました。UITextField
UITextFieldDelegate
- (void)textViewDidChangeSelection:(UITextView *)textView
でトークンを目立たせたかったのでUITextView
、 を使用NSAttributedString
してテキストを強調表示することにしました。トークンは通常のテキストとは異なる属性を持つようになったため、次を使用して、選択したテキストがトークンであるかどうかを確認できます。
- (id)attribute:(NSString *)attributeName atIndex:(NSUInteger)index effectiveRange:(NSRangePointer)aRange
UITextPosition
指定された aに対して any を受け取り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;
}
このメソッドを使用すると、選択範囲の and がトークン内またはトークンに隣接しているかどうかを計算できstart
、end
UITextPosition
新しい範囲の作成に進み、それを新しい選択範囲として設定できます。
[textView setSelectedRange:NSRangeMake(newStartInt,newEndInt-newStartInt];