我无法解决这个问题:我有一个UISearchBar
子类,该子类与UISeachDisplayControlller
中的UITableViewController
一起使用,该子类在左侧添加了一个按钮,并使UISearchTextField
较小,因此可以同时适合两种视图。
我很难在layoutSubviews
中手动设置框架,即使在整个项目中都使用AutoLayout
时也是如此。
代码看起来像这样:
UIView *searchBarView = [self.subviews objectAtIndex:0];
[searchBarView addSubview:_annotationsButton];
for (UIView *subview in searchBarView.subviews) {
if ([subview isKindOfClass:[UITextField class]]) {
// Change the border color of the UISearchTextField
[subview.layer setBorderWidth:1.0];
[subview.layer setBorderColor:[UIColor colorFromHexString:@"#77848D"].CGColor];
[subview.layer setCornerRadius:2.0];
}
}
[self setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]]];
self.separator = [[UIView alloc] initWithFrame:CGRectMake(0, self.bounds.size.height-1, self.bounds.size.width, 1)];
[self.separator setBackgroundColor:[UIColor colorFromHexString:@"#d6d0cc"]];
[searchBarView addSubview:self.separator];
奇怪的结果是这样的:
如您所见,该条显示为灰色。
layoutSubviews
方法如下:- (void)layoutSubviews{
[super layoutSubviews];
UIView *searchBarView = [self.subviews objectAtIndex:0];
for (UIView *subview in searchBarView.subviews) {
if ([subview isKindOfClass:[UITextField class]]) {
CGRect textFieldFrame = [subview frame];
if (!subview.isFirstResponder) {
self.originalFrame = textFieldFrame;
CGRect newTextFieldRect = CGRectMake(self.originalFrame.origin.x + self.originalFrame.size.width /2,
self.originalFrame.origin.y,
self.originalFrame.size.width /2 - kPadding,
self.originalFrame.size.height);
[subview setFrame:newTextFieldRect];
CGRect annotationsButtonFrame = CGRectMake(kPadding,
self.originalFrame.origin.y,
self.originalFrame.size.width /2 - kPadding,
self.originalFrame.size.height);
[self.annotationsButton setFrame:annotationsButtonFrame];
[self.annotationsButton setHidden:NO];
}
else {
[self.annotationsButton setHidden:YES];
}
}
}
[self.separator setFrame:CGRectMake(0, self.bounds.size.height-1, self.bounds.size.width, 1)];
}
在这种方法中,我只是调整了
UISearchBarTextField
和_annotationsButton的框架,以使它们不重叠。 最佳答案
只要背景设置了图像,就会发生这种情况。
我设法将标准设置为半透明,并使用以下行:
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
self.searchBarStyle = UISearchBarStyleMinimal;
}
我已解决问题。
关于ios - 自定义UISearchBar在UINavigationBar下的色彩不正确,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22634540/