iosswiftsubviews

Traverse UIView.subviews to get button is swift


In my Objective-C code, I can use this method to find a view.subviews's button:

-(UIButton*)findButtonInView: (UIView*)v {
    for (UIView *subView in v.subviews) {
        if ([subView isKindOfClass:[UIButton class]]) {
            return (UIButton*)subView;
        }
        else if ([subView isKindOfClass:[UIView class]]) {
            UIButton* btn = [self findButtonInView:subView];
            if(btn) {
                return btn;
            }
        }
    }
    return nil;
}

UIButton* searchButton = [self findButtonInView:self.searchBar];

But how can I make a method to find button in view by Swift?

As you know I can not return nil like in this Swift method:

class func findButtonInView(_ view:UIView) -> UIButton {}

Solution

  • class func findButtonInView(_ view:UIView) -> UIButton?{}