简体   繁体   中英

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.

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

Simple set the selected range appropriately:

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

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

}

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];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM