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?
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.
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+
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]; } }
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 { // ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With