Alright, after trying out a ton of methods to get around this, I decided to just use UITextView
in place of UITextField
as UITextFieldDelegate
has the following method:
- (void)textViewDidChangeSelection:(UITextView *)textView
Since I wanted my tokens to stand out in my UITextView
, I decided to use NSAttributedString
to highlight my text. Since the tokens are now has attributes different form the normal text, I can use the following to check if the selected text is a token:
- (id)attribute:(NSString *)attributeName atIndex:(NSUInteger)index effectiveRange:(NSRangePointer)aRange
I wrote a method that will take in any UITextPosition
for a given UITextView
and return the nearest left start of a token in the form of a NSInteger
. This is so that I can easily use it to make a NSRange
afterwards:
- (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;
}
Using this method, I could compute if the start
and end
UITextPosition
of a selection is in or adjacent to a token, and I can proceed to create a new range and set it as the new selection:
[textView setSelectedRange:NSRangeMake(newStartInt,newEndInt-newStartInt];