AugustoQ
AugustoQ

Reputation: 507

How to select all text in a UITextField?

I have a small project where people can create items to be shown on a list, and when they first create an item, it get a generic name: "New Item", so I wanted the app to know to select the whole title in order to make it easier for the user to rename it. I went online and spent a good long time searching for a way to do it, but every way I tried went wrong. This was the last thing I've done, and what this part of my code looks like:

if ([self.detailItem.title isEqualToString:@"New Item"]) {

    self.titleField.selectedTextRange = nil;
}

But I've also tried [self.titleField selectAll:self] but it didn't work either, neither, as I've said, did anything else I've tried.

Any ideas on what I should do?

If you need anymore code just let me know what part of it and I'll edit it into this question.

Thanks for any help.

Upvotes: 0

Views: 240

Answers (3)

lifjoy
lifjoy

Reputation: 2188

This worked better for me:

- (void)selectAllTextInField:(UITextField *)textField {
    UITextPosition  *theStart   = [textField beginningOfDocument];
    UITextPosition  *theEnd     = [textField endOfDocument];
    UITextRange     *theRange   = [textField textRangeFromPosition:theStart toPosition:theEnd];
    [textField setSelectedTextRange:theRange];
}

Upvotes: 0

wottle
wottle

Reputation: 13619

Simple set the selected range appropriately:

if ([self.detailItem.title isEqualToString:@"New Item"]) {

    self.titleField.selectedRange = NSMakeRange(0, self.titleField.text.length);

}

Upvotes: 1

almas
almas

Reputation: 7187

UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 30, 320, 30)];
[self.view addSubview:textField];
textField.placeholder = @"my placeholder text";

Upvotes: 2

Related Questions