Styling the cancel button in a UISearchBar

前端 未结 21 1431
-上瘾入骨i
-上瘾入骨i 2020-12-02 09:13

I have a UISearchBar that has a cancel button (it\'s displayed using -(void)setShowsCancelButton:animated). I\'ve changed the tintColor of the sear

21条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 09:57

    I have many UISearchBar items throughout my app, so I wrote this category to add a property so you can access mySearchBar.cancelButton. (If you're new to categories, read more about extending objects with Categories here.)

    Keep in mind you should only access this when the Cancel button is visible because UISearchBar seems to create a new button object every time it shows. Don't save the pointer to the cancelButton, just get it when needed:

    @interface UISearchBar (cancelButton)
    
    @property (readonly) UIButton* cancelButton;
    
    - (UIButton *) cancelButton;
    
    @end
    
    @implementation UISearchBar (cancelButton)
    
    - (UIButton *) cancelButton {
        for (UIView *subView in self.subviews) {
            //Find the button
            if([subView isKindOfClass:[UIButton class]])
            {
                return (UIButton *)subView;
            }
        }
    
        NSLog(@"Error: no cancel button found on %@", self);
    
        return nil;
    }
    
    @end
    

提交回复
热议问题