当前位置: 动力学知识库 > 问答 > 编程问答 >

iphone - 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.

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.

网友答案:

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

UIBarButtonItem *cancelButton = [UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil];
网友答案:

So I override -layoutSubViews with this, but theres 2 issues I have

I hate iterating through the views to find the matching view, and it messes up the animation a little bit

- (UIButton *)cancelButton {
    for (UIView *v in self.subviews) {
        if ([v isKindOfClass:[UIButton class]]) {
            NSString *caption = [[((UIButton *)v) titleLabel] text];
            if ([caption isEqualToString:@"Cancel"] )
                return (UIButton *)v;
        }
    }
    return nil;
}

- (BOOL)cancelButtonIsShowing {
    return ([self cancelButton] != nil);
}

- (void)layoutSubviews {
    [super layoutSubviews];
    if ([self cancelButtonIsShowing]) {
        UIButton *cancelButton = [self cancelButton];

        UIImage *i = [UIImage imageNamed:@"Cancel_BTN"];
        CGRect f = CGRectMake(267, 5, i.size.width, i.size.height);
        cancelButton.frame = f;
    }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: