实现iOS 8 Safari可伸缩的NavigationBar

原创blog,转载请注明出处
http://blog.csdn.net/hello_hwc?viewmode=contents
欢迎关注我的iOS SDK详解专栏
http://blog.csdn.net/column/details/huangwenchen-ios-sdk.html

Demo效果
实现iOS 8 Safari可伸缩的NavigationBar_第1张图片

注:本文并没有完全实现Safari的navBar功能:比如textfield开始编辑的时候navBar恢复正常,比如监听Scrollview的速度。个人觉得,懂得如何伸缩以及控制textfile的大小颜色,其他的都不是问题。

实现过程

在ViewDidload中,设置配置textfield,这里要注意一点,一定要把textfield放到一个Containview里,否则后文的transform将不会得到想要的效果。

    CGFloat screenWidth = [[UIScreen mainScreen] bounds].size.width;
    UIView * containview = [[UIView alloc] initWithFrame:CGRectMake(0, 0,screenWidth - 30, 30)];
    self.navTextfield = [[UITextField alloc] initWithFrame:CGRectMake(0, 0,screenWidth - 30, 30)];
    self.navTextfield.borderStyle = UITextBorderStyleNone;
    self.navTextfield.textAlignment = NSTextAlignmentCenter;
    self.navTextfield.backgroundColor = [self lightGrayWithAplpa:1.0];
    self.navTextfield.layer.cornerRadius = 5.0;
    self.navTextfield.layer.masksToBounds = true;
    [containview addSubview:self.navTextfield];
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    self.navigationItem.titleView = containview;
    //设定初始值
    self.navTextfield.text = @"www.baidu.com";

在scrollViewDidScroll中,通过Offset,来动态的改变颜色和Transform

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat offsetY = scrollView.contentOffset.y;
    //定义,移动40距离的时候,缩小到最小
    CGFloat progress;
    if (offsetY > -64) {
        progress = (offsetY + 64)/40;
        progress = MIN(progress, 1);
    }else{
        progress = 0;
    }
    //处理Scale与Alpha
    CGFloat scale = 1 - 0.4*progress;
    CGFloat alpha = 1 - progress;
    self.navTextfield.backgroundColor = [self lightGrayWithAplpa:alpha];
    //计算要位移的距离
    CGFloat navHeight = 44;
    CGFloat navOffSetY = -1 * navHeight * 0.4 * progress;
    CGFloat textFieldOffsetY = navHeight * 0.2 * progress;
    CGAffineTransform scaleTran = CGAffineTransformMakeScale(scale, scale);
    CGAffineTransform transTran = CGAffineTransformMakeTranslation(0, textFieldOffsetY);
    self.navTextfield.transform = CGAffineTransformConcat(scaleTran, transTran);
    self.navigationController.navigationBar.transform = CGAffineTransformMakeTranslation(0,navOffSetY);
}

这里的颜色函数为这个

-(UIColor *)lightGrayWithAplpa:(CGFloat)alpha{
    return [UIColor colorWithRed:225.0/255 green:225.0/255 blue:225.0/255 alpha:alpha];
}

你可能感兴趣的:(ios,Safari,导航,nagivation)