-[UITextField selectedText]
Although UITextField does not have a selectedText method, it conforms to the UITextInput protocol. Thus, you can use the necessary properties and methods of the UITextInput protocol to determine selectedText for UITextField *textField (or any object that conforms to the UITextInput protocol, such as UITextView ).
NSString *selectedText = [textField textInRange:textField.selectedTextRange]; NSLog(@"selectedText: %@", selectedText);
As an aside, you can also use the necessary properties and methods of UITextInput to compute selectedRange a UITextField *textField .
UITextRange *selectedTextRange = textField.selectedTextRange; NSUInteger location = [textField offsetFromPosition:textField.beginningOfDocument toPosition:selectedTextRange.start]; NSUInteger length = [textField offsetFromPosition:selectedTextRange.start toPosition:selectedTextRange.end]; NSRange selectedRange = NSMakeRange(location, length); NSLog(@"selectedRange: %@", NSStringFromRange(selectedRange));
-[UITextFieldDelegate textFieldDidChangeSelection:]
Although UITextFieldDelegate does not declare the delegate method textFieldDidChangeSelection: for example -[UITextViewDelegate textViewDidChangeSelection:] , you can still connect when the UITextField selection UITextField changed. To do this, subclass UITextField and use the swizzling method to add your own code to your own implementation of textField.inputDelegate -[UITextInputDelegate selectionDidChange:] .
// MyTextField.h #import <UIKit/UIKit.h> @interface MyTextField : UITextField @end // MyTextField.m #import <objc/runtime.h>
ma11hew28 Jul 06 2018-12-12T00: 00Z
source share