Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change frame of cancel button in UISearchBar

I have the following code to change the appearance of the UISearchBar in my application and it can be seen in the image below also:

for(int i = 0; i < [[searchBar subviews] count]; i++){
    UIView *subView = [[searchBar subviews] objectAtIndex:i];
    if([[NSString stringWithFormat:@"%@", [subView class]] isEqualToString:@"UINavigationButton"]){
        UIButton *cancelButton = (UIButton *)subView;

        CGRect buttonFrame = cancelButton.frame;
        buttonFrame.size.height = 52;
        [cancelButton setFrame:buttonFrame];

        [cancelButton setTitle:@"Cancel" forState:UIControlStateNormal];
        [cancelButton setBackgroundImage:[UIImage imageNamed:@"cancel.png"] forState:UIControlStateNormal];
        [cancelButton setBackgroundImage:[UIImage imageNamed:@"cancel_pressed.png"] forState:UIControlStateHighlighted];
    }
}

As you can see I am trying to change the height of the button contained in the UISearchBar with no luck. I do get reference to the button as I can change the text and the background Image is changed just not the height of the frame. I would just like the height of the button to be the same as the search box at 52px.

enter image description here

EDIT:

I have found a really hacky solution, but it's not very elegant of adding a UIButton as the subview of the Cancel Button. It does the job but as I say it's not very nice.

like image 976
SamRowley Avatar asked Oct 04 '22 22:10

SamRowley


1 Answers

Actually you could use method below to access the cancel Button:

UIBarButtonItem *cancelButton = [UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil];
like image 178
JackieLam Avatar answered Oct 13 '22 11:10

JackieLam