Get the current first responder without using a private API

前端 未结 28 1829
夕颜
夕颜 2020-11-22 05:03

I submitted my app a little over a week ago and got the dreaded rejection email today. It tells me that my app cannot be accepted because I\'m using a non-public API; specif

相关标签:
28条回答
  • 2020-11-22 05:59

    Using Swift and with a specific UIView object this might help:

    func findFirstResponder(inView view: UIView) -> UIView? {
        for subView in view.subviews as! [UIView] {
            if subView.isFirstResponder() {
                return subView
            }
            
            if let recursiveSubView = self.findFirstResponder(inView: subView) {
                return recursiveSubView
            }
        }
        
        return nil
    }
    

    Just place it in your UIViewController and use it like this:

    let firstResponder = self.findFirstResponder(inView: self.view)
    

    Take note that the result is an Optional value so it will be nil in case no firstResponder was found in the given views subview hierarchy.

    0 讨论(0)
  • 2020-11-22 06:04

    Just it case here is Swift version of awesome Jakob Egger's approach:

    import UIKit
    
    private weak var currentFirstResponder: UIResponder?
    
    extension UIResponder {
    
        static func firstResponder() -> UIResponder? {
            currentFirstResponder = nil
            UIApplication.sharedApplication().sendAction(#selector(self.findFirstResponder(_:)), to: nil, from: nil, forEvent: nil)
            return currentFirstResponder
        }
    
        func findFirstResponder(sender: AnyObject) {
            currentFirstResponder = self
        }
    
    }
    
    0 讨论(0)
  • 2020-11-22 06:05

    You can choose the following UIView extension to get it (credit by Daniel):

    extension UIView {
        var firstResponder: UIView? {
            guard !isFirstResponder else { return self }
            return subviews.first(where: {$0.firstResponder != nil })
        }
    }
    
    0 讨论(0)
  • 2020-11-22 06:06

    This is what I did to find what UITextField is the firstResponder when the user clicks Save/Cancel in a ModalViewController:

        NSArray *subviews = [self.tableView subviews];
    
    for (id cell in subviews ) 
    {
        if ([cell isKindOfClass:[UITableViewCell class]]) 
        {
            UITableViewCell *aCell = cell;
            NSArray *cellContentViews = [[aCell contentView] subviews];
            for (id textField in cellContentViews) 
            {
                if ([textField isKindOfClass:[UITextField class]]) 
                {
                    UITextField *theTextField = textField;
                    if ([theTextField isFirstResponder]) {
                        [theTextField resignFirstResponder];
                    }
    
                }
            }
    
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题