Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to find which text field is active ios

Tags:

ios

I am trying to find which textfield is active for when the I move the view when the keyboard rises. I am trying to set a property in my viewcontroller from the subview of a scrollview.

This is the code I use to display the view in the scrollview

-(void)displayView:(UIViewController *)viewController{  [[viewFrame subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];  [viewFrame scrollRectToVisible:CGRectMake(0, 0, 1, 1)                         animated:NO];  [viewFrame addSubview: viewController.view];  _currentViewController = viewController; } 

--EDIT--

I have changed my way of thinking about this problem. Sorry for the question being ambiguous when I posted it. I was exhausted at the time and it made sense in my head.

A different but similar question: Is there a common subclass of both UITextArea and UITextView that will give me the origin of the firstResponder? Or will I have to check also the class of the firstResponder before I can find the origin?

like image 534
Lost Sorcerer Avatar asked Aug 29 '12 08:08

Lost Sorcerer


People also ask

How do I know if my textfield is a first responder?

You could keep track of which text field is the first responder by either setting your view controller to be the delegate object of all text fields and then when your subclassed text fields gets the " becomeFirstResponder " method call, tell your view controller which text field is the current one.

What is textfield in iOS?

A control that displays an editable text interface. iOS 13.0+ iPadOS 13.0+ macOS 10.15+ Mac Catalyst 13.0+ tvOS 13.0+ watchOS 6.0+


2 Answers

You need to search for an object that has become a first responder. First responder object is the one using the keyboard (actually, it is he one having focus for user input). To check which text field uses the keyboard, iterate over your text fields (or just over all subviews) and use the isFirstResponder method.

EDIT: As requested, a sample code, assuming all text fields are a subview of the view controller's view:

for (UIView *view in self.view.subviews) {     if (view.isFirstResponder) {         [self doSomethingCleverWithView:view];     } } 
like image 70
Xilexio Avatar answered Sep 20 '22 18:09

Xilexio


I did an extension for this.

public extension UIResponder {      private struct Static {         static weak var responder: UIResponder?     }      public static func currentFirst() -> UIResponder? {         Static.responder = nil         UIApplication.shared.sendAction(#selector(UIResponder._trap), to: nil, from: nil, for: nil)         return Static.responder     }      @objc private func _trap() {         Static.responder = self     } } 

Use:

if let activeTextField = UIResponder.currentFirst() as? UITextField {     // ... } 
like image 32
Stanislav Smida Avatar answered Sep 19 '22 18:09

Stanislav Smida