UITextFeild默认选中文本
方法1:selectAll:
[textFeild selectAll:nil]; //全选
[textFeild selectAll:self];//全选并弹出UIMenuController菜单
//利用`selectedTextRange`
//@property (nullable, readwrite, copy) UITextRange *selectedTextRange;
[textFeild setSelectedTextRange:[textFeild textRangeFromPosition:textFeild.beginningOfDocument toPosition:textFeild.endOfDocument]];
使用举例
- (void)showWCPlaceNameInputView{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请输入名称" message:nil preferredStyle:UIAlertControllerStyleAlert];
WS(weakSelf);
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
}];
UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
}];
[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.text = weakSelf.userInputLocationDescription;
textField.textAlignment = NSTextAlignmentCenter;
[textField addTarget:self action:@selector(handleTextFieldTextDidChange:) forControlEvents:UIControlEventEditingChanged];
[textField addTarget:self action:@selector(handleTextFieldTextDidBegin:) forControlEvents:UIControlEventEditingDidBegin];
}];
// Add the actions.
[alertController addAction:cancelAction];
[alertController addAction:otherAction];
[self presentViewController:alertController animated:YES completion:nil];
}
- (void)handleTextFieldTextDidBegin:(UITextField *)textFeild{
dispatch_async(dispatch_get_main_queue(), ^{
[textFeild selectAll:nil]; //直接选中
//[textFeild selectAll:self]; 默认选中切会弹出UIMenuController
//[textFeild setSelectedTextRange:[textFeild textRangeFromPosition:textFeild.beginningOfDocument toPosition:textFeild.endOfDocument]];
});
}
- (void)handleTextFieldTextDidChange:(UITextField *)textFeild{
self.userInputLocationDescription = textFeild.text.trimed;
}
##参考链接
https://stackoverflow.com/questions/1689911/programmatically-select-all-text-in-uitextfield