iOS (导航条)navBar 透明

现实开发中会遇到一种情况。UI会把导航条做成透明的,滑动的时候才逐渐显现。不透明的时候样子是这样的。

是挺难看的。

所以想要制作透明的导航条 就要知道一个方法,一个属性

这时 UIImage 这个图看来是必须要画一个了

- (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [color setFill];
    CGContextFillRect(context, rect);
    UIImage *imgae = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return imgae;
}

当然也可以给UIImage添加类目

UIImage+colorImge.h

#import <UIKit/UIKit.h>

@interface UIImage (colorImge)
+ (UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)size;
@end

UIImage+colorImge.m

#import "UIImage+colorImge.h"

@implementation UIImage (colorImge)

+ (UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)size {
    
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    CGContextAddEllipseInRect(context, rect);
    UIGraphicsEndImageContext();
    return image;
}

@end

这样就能直接初始化一个UIImage了

这时我们就可以让导航透明了

 

 

 

 效果如图

这时想要做到滑动时逐渐变色类似下图

需要在

- (void)scrollViewDidScroll:(UIScrollView *)scrollView ;方法中做文章了。因为tableVIew继承自scrollView

在这个方法中判断tableVIew的contentOffset.y。先看代码

当前的透明度 = (tableView.contentOffset.y - tableView.contentOffset.y的起点) / (完全不透明的终点 + tableView.contentOffset.y的起点) 一般没做修改的话 tableView.contentOffset.y的起点是0, 完全不透明的终点 就是看你心情 滑动多远的时候导航条全变色。

如果有时间的话可以做做封装。面对多种不同的情况做不同的效果

 

posted @ 2017-04-08 10:36  唐宋元明清。  阅读(3300)  评论(0编辑  收藏  举报