5

我有以下代码来更改我的应用程序中 UISearchBar 的外观,它也可以在下图中看到:

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];
    }
}

如您所见,我正在尝试更改 UISearchBar 中包含的按钮的高度,但没有成功。我确实得到了对按钮的引用,因为我可以更改文本并且背景图像被更改,而不是框架的高度。我希望按钮的高度与 52px 的搜索框相同。

在此处输入图像描述

编辑:

我找到了一个非常 hacky 的解决方案,但是添加 UIButton 作为取消按钮的子视图并不是很优雅。它完成了这项工作,但正如我所说,它不是很好。

4

2 回答 2

4

其实你可以使用下面的方法来访问取消按钮:

UIBarButtonItem *cancelButton = [UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil];
于 2013-12-05T11:25:00.887 回答
0

所以我-layoutSubViews用这个覆盖,但我有两个问题

我讨厌遍历视图以找到匹配的视图,这会使动画有点混乱

- (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;
    }
}
于 2013-07-11T13:51:58.023 回答