我有以下代码来更改我的应用程序中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作为Cancel Button的子视图并不是很优雅。它做的工作,但正如我说它不是很好。
答案 0 :(得分:3)
实际上你可以使用下面的方法来访问取消按钮:
UIBarButtonItem *cancelButton = [UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil];
答案 1 :(得分:0)
所以我用这个覆盖-layoutSubViews
,但是我有2个问题
我讨厌在视图中迭代以找到匹配的视图,它会稍微搞乱动画
- (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;
}
}