将叠加视图添加到UINavigationBar

时间:2015-09-03 17:09:51

标签: ios objective-c

我有一个透明的appearance设置UINavigationBar,没有涉及子类。

我想添加一个将会"行动"作为UISearchBar的背景,此视图还具有展开/折叠自定义搜索栏(不是UINavigationBar的子类)。我将此视图称为OverlayView。

原因主要是因为背景颜色应该动态变化。

我已将我的OverlayView添加为userInteractionEnabled的子视图。它显示正确,它做我需要的一切。但是当我点击搜索文本字段时,我不会选择点按,即我无法在搜索字段中输入任何内容。

我的OverlayView和YES上的UINavigationBar设置为Style.xml

我应该在其他地方添加我的OverlayView吗?如何才能识别该视图上的水龙头?

2 个答案:

答案 0 :(得分:1)

尝试这可能会对您有所帮助。

UISearchBar *searchBar = [UISearchBar new];
searchBar.showsCancelButton = YES;
[searchBar sizeToFit];
[searchBar becomeFirstResponder];
UIView * OverlayView = [[UIView alloc]initWithFrame:searchBar.bounds];
[OverlayView addSubview:searchBar];
self.navigationItem.titleView = OverlayView;

答案 1 :(得分:0)

我将UINavigationBar子类化为绘制自定义背景图层。 可能,我的代码会帮助你

#import "OCNavigationBar.h"
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

#define UIColorFromRGBAlpha(rgbValue, alphaValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:alphaValue]


@implementation OCNavigationBar {
    UIView * gradientView;
}

- (void)drawRect:(CGRect)rect {
    if (gradientView == NULL) {
        CGFloat statusBarHeight = [UIApplication sharedApplication].statusBarFrame.size.height;
        CGRect gradientRect = CGRectMake(self.frame.origin.x, - statusBarHeight, self.frame.size.width, self.frame.size.height + statusBarHeight);

        gradientView = [[UIView alloc] initWithFrame:gradientRect];
        gradientView.backgroundColor = [UIColor yellowColor];

        UIColor * gradientColor1 = UIColorFromRGB(0x242430);
        UIColor * gradientColor2 = UIColorFromRGB(0x252532);

        CAGradientLayer *gradient = [CAGradientLayer layer];
        gradient.frame = CGRectMake(gradientRect.origin.x, 0, gradientRect.size.width, gradientRect.size.height);
        gradient.colors = [NSArray arrayWithObjects:(id)[gradientColor1 CGColor], (id)[gradientColor2 CGColor], nil];
        [gradientView.layer insertSublayer:gradient atIndex:0];

        [self insertSubview:gradientView atIndex:-1];
    }
}

#pragma mark - Tools

- (void)insertSubview:(UIView *)view atIndex:(NSInteger)index
{
    [super insertSubview:view atIndex:index+1];
}