How do I place a UILabel next to the last character of a UITextField?

I'm trying to achieve the same effect as the new Facebook status field: put something next to the last character that cannot be changed or selected by the user (eg tag: "with Joh Doe").

What is the best way to achieve it?

thank

Nick

Screenshot

+3


source to share


1 answer


A simpler solution would be to simply make the last n characters in the TextView not editable. Then let the TextView handler move and wrap the text as needed. I would guess this is what Facebook is doing, just with some text attribute at the end.

In your ViewControllers.h, make sure the viewController matches the UITextViewDelegate as follows.

@interface ViewController : UIViewController <UITextViewDelegate>

      

Then, in the method, viewDidLoad:

set the delegate for the UITextView to the ViewController. You can also add your own anchor text.

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.myTextView.delegate = self;
    self.myTextView.text = " posted by Mike";
}

      

Then we will use the method shouldChangeCharactersInRange:

to prevent the user from editing the text at the end that you want to keep.



- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    BOOL deleteKeyPressed = ([text length] == 0 && range.length > 0);

    if( range.location > (textView.text.length - @" - posted by Mike".length) || (deleteKeyPressed && range.location > (textView.text.length - @" - posted by Mike".length)) )
    {
        return NO;
    }
    return YES;
}

      

I think this should get you started and make your life easier than finding the end of the last text and then putting another view at the end, which you might need to wrap if you run out of space.

So, to prevent the user from selecting the "reserved" text, add the following delegate method to your ViewController.m:

-(void) textViewDidChangeSelection:(UITextView *)textView
{
    if( textView.selectedRange.location > (textView.text.length - @" - posted by Mike".length) )
    {
        [textView setSelectedRange:NSMakeRange((textView.text.length - @" - posted by Mike".length), 0 )];
    }
}

      

You will still have to handle if the user selects all of the text and chooses "cut" or "paste", but that should just be a special case in shouldChangeTextInRange

. I will let you understand that one of them should not be heavy. Much easier of course than trying to dynamically position, size and wrap the TextView in another TextView.

+4


source







All Articles