2
下自定義錯誤的UISearchBar色彩,我不能讓我的頭圍繞這個問題:我有一個UISearchBar
子類,我使用的是在UITableViewController
,增加了左側的一個按鈕UISeachDisplayControlller
,使UISearchTextField
小,所以它可以適合兩種觀點。UINavigationBar的
我在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所以它們不重疊。