在UINavigationBar下自定义UISearchBar错误色调

时间:2014-03-25 12:24:37

标签: ios ios7 uinavigationbar uisearchbar

我无法理解这个问题:我有一个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];

奇怪的结果如下: enter image description here

如您所见,条形图显示为灰色。

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的帧,使它们不重叠。

1 个答案:

答案 0 :(得分:0)

每当背景设置为图像时,就会发生这种情况。 我设法将条形设置为半透明并使用此行:

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
        self.searchBarStyle = UISearchBarStyleMinimal;
}

我解决了我的问题。

相关问题