How to Get Selected Text from Uitextfield in Iphone

how to get selected text from uitextfield in iphone?

-[UITextField selectedText]

Although UITextField doesn't have a selectedText method, it conforms to the UITextInput protocol. So, you can use the required properties & methods of the UITextInput protocol to determine the selectedText of a UITextField *textField (or any object that conforms to the UITextInput protocol, such as a UITextView).

NSString *selectedText = [textField textInRange:textField.selectedTextRange];
NSLog(@"selectedText: %@", selectedText);

As an aside, you can also use the required properties & methods of the UITextInput to calculate the selectedRange of 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 doesn't declare a textFieldDidChangeSelection: delegate method like -[UITextViewDelegate textViewDidChangeSelection:], you can still hook into when the selection of a UITextField has changed. To do so, subclass UITextField and use method swizzling to add your own code to the textField.inputDelegate's native implementation of -[UITextInputDelegate selectionDidChange:].

// MyTextField.h

#import <UIKit/UIKit.h>

@interface MyTextField : UITextField

@end

// MyTextField.m

#import <objc/runtime.h>
#import "MyTextField.h"

UIKIT_STATIC_INLINE void mySelectionDidChange(id self, SEL _cmd, id<UITextInput> textInput);

@implementation MyTextField {
BOOL swizzled;
}

#pragma mark - UIResponder

// Swizzle here because self.inputDelegate is set after becomeFirstResponder gets called.
- (BOOL)becomeFirstResponder {
if ([super becomeFirstResponder]) {
[self swizzleSelectionDidChange:YES];
return YES;
} else {
return NO;
}
}

// Unswizzle here because self.inputDelegate may become the inputDelegate for another UITextField.
- (BOOL)resignFirstResponder {
if ([super resignFirstResponder]) {
[self swizzleSelectionDidChange:NO];
return YES;
} else {
return NO;
}
}

#pragma mark - Swizzle -[UITextInput selectionDidChange:]

// Swizzle selectionDidChange: to "do whatever you want" when the text field's selection has changed.
// Only call this method on the main (UI) thread because it may not be thread safe.
- (void)swizzleSelectionDidChange:(BOOL)swizzle {
if (swizzle == swizzled || ![self respondsToSelector:@selector(inputDelegate)]) return; // 4.3

Class inputDelegateClass = object_getClass(self.inputDelegate);
SEL mySelector = @selector(mySelectionDidChange:);
class_addMethod(inputDelegateClass, mySelector, (IMP)mySelectionDidChange, "v@:@");
Method myMethod = class_getInstanceMethod(inputDelegateClass, mySelector);
Method uiKitMethod = class_getInstanceMethod(inputDelegateClass, @selector(selectionDidChange:));
method_exchangeImplementations(uiKitMethod, myMethod);
swizzled = swizzle;
// NSLog(@"swizzled? %i", method_getImplementation(uiKitMethod) == (IMP)venmo_selectionDidChange);
}

@end

UIKIT_STATIC_INLINE void mySelectionDidChange(id self, SEL _cmd, id<UITextInput> textInput) {
// Call the native implementation of selectionDidChange:.
[self performSelector:@selector(mySelectionDidChange:) withObject:textInput];

// "Do whatever you want" with the selectedText below.
NSString *selectedText = [textInput textInRange:textInput.selectedTextRange];
NSLog(@"selectedText: %@", selectedText);
}

How to find the selected text field in iOS

- (IBAction)buttonPressed:(id)sender {

if([textbox1 isFirstResponder]){
//Cursor on textbox1
texbox1.text=@"User";
}
else if([textbox2 isFirstResponder]){
//Cursor on textbox2
textbox2.text =@"Admin";
}
else{

NSLog(@"None of them have cursor");
}
}

Can I select a specific block of text in a UITextField?

With UITextField, you cannot. But if you see the headers, you have _selectedRange and others that might be used if you add some categories to it ;)



Update for iOS5 and above :

Now UITextField and UITextView conform to UITextInput protocol so it is possible :)

Selecting the last 5 characters before the caret would be like this:

// Get current selected range , this example assumes is an insertion point or empty selection
UITextRange *selectedRange = [textField selectedTextRange];

// Calculate the new position, - for left and + for right
UITextPosition *newPosition = [textField positionFromPosition:selectedRange.start offset:-5];

// Construct a new range using the object that adopts the UITextInput, our textfield
UITextRange *newRange = [textField textRangeFromPosition:newPosition toPosition:selectedRange.start];

// Set new range
[textField setSelectedTextRange:newRange];

Selected text doesn't appear on the UITextField

The reason your solution is updating only one text field is because you're updating the text of only that text field. In this line phonenumber.text = String(contactNumber.suffix(10)) you change only phonenumber's text. A good solution would be as follows:

Create a temp UITextField to store selected text field reference

@IBOutlet weak var phonenumber: UITextField!
@IBOutlet weak var phonenumber1: UITextField!
@IBOutlet weak var phonenumber2: UITextField!
var currentTextField: UITextField?

And use that text field in text field delegate methods

extension SelfTestTimer: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
currentTextField = nil
textField.resignFirstResponder()
return true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField.hasText{
//dont do anything
}else{
currentTextField = textField
contactPicker.delegate = self
self.present(contactPicker, animated: true, completion: nil)
}
return
}
}

Assign selected contact number in that text field

func setNumberFromContact(contactNumber: String) {
var contactNumber = contactNumber.replacingOccurrences(of: "-", with: "")
contactNumber = contactNumber.replacingOccurrences(of: "(", with: "")
contactNumber = contactNumber.replacingOccurrences(of: ")", with: "")
guard contactNumber.count >= 10 else {
dismiss(animated: true) {
self.presentAlert(alertTitle: "", alertMessage: "A maximum of 10 contacts allowed per session", lastAction: nil)
}
return
}
currentTextField?.text = String(contactNumber.suffix(10))
}

How can I get the selected text frame from a UITextView

I think [UITextInput selectedTextRange] and [UITextInput caretRectForPosition:] is what you are looking for.

[UITextInput selectedTextRange] returns the selected range in character

[UITextInput caretRectForPosition:] returns the CGRect of the character range in this input.

UITextView conforms to UITextInput (since iOS 5), so you can use these methods for your UITextView instance.

It is going to be something like this.

UITextRange * selectionRange = [textView selectedTextRange];
CGRect selectionStartRect = [textView caretRectForPosition:selectionRange.start];
CGRect selectionEndRect = [textView caretRectForPosition:selectionRange.end];
CGPoint selectionCenterPoint = (CGPoint){(selectionStartRect.origin.x + selectionEndRect.origin.x)/2,(selectionStartRect.origin.y + selectionStartRect.size.height / 2)};

EDIT : Since the sample code became a little hard to get, I added an image for complementing.

An image that illustrates what local variables represent

Get selected text in a UITextView

What is happening is that UITextView method textInRange have been renamed to text(in: Range) since Swift 3. Btw you forgot to add the let keyword in your sentence:

if let range = textView.selectedTextRange {
UIPasteboard.general.string = textView.text(in: range)
}


Related Topics



Leave a reply



Submit