您好,欢迎来到二三娱乐。
搜索
您的当前位置:首页iOS开发:搜索框的简单使用、改变返回按钮的颜色

iOS开发:搜索框的简单使用、改变返回按钮的颜色

来源:二三娱乐
效果GIF.gif

UISearchBar的使用,在导航栏上添加搜索框:

UISearchBar *searchBar = [[UISearchBar alloc] init];
searchBar.placeholder = @"搜索";
searchBar.showsCancelButton = YES; //显示关闭按钮
//这个主要是为了把cancel按钮改变成中文的,如果在plist文件中设置过,则不需要此处
UIButton *cancelBtn = [searchBar valueForKey:@"cancelButton"]; //首先取出cancelBtn
//这样就可以随便设置这个按钮了
[cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
searchBar.searchBarStyle = UISearchBarStyleMinimal; //去掉searchBar的周边颜色
searchBar.frame = CGRectMake(0, 7, [UIScreen mainScreen].bounds.size.width, 30);
searchBar.delegate = self;
self.navigationItem.titleView = searchBar;

改变返回按钮的颜色

项目中使用到了web页面,由于web页面可能背景色不同,想要使导航栏的背景色和web的背景色一致,此时返回按钮的文案颜色以及‘返回箭头’颜色可能也需要改变;

如果直接设置返回按钮的颜色,确实可以改变,但是如果自定义了返回按钮文案,下面的方法就没有效果了

self.navigationController.navigationBar.tintColor = [UIColor redColor];

如果在push到web页面之前,设置返回按钮按钮的文案,如下:

UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
self.navigationItem.backBarButtonItem = item;

这样如果有很多个页面都push到了这个web页面,会很不灵活

返回箭头返回我是自定义了一个View,然后把自定义的View转换成图片作为按钮的背景图,而按钮又作为返回按钮leftBarButtonItem,返回箭头我是通过UIBezierPath画出来的;下面是返回箭头的绘制:

- (void)drawRect:(CGRect)rect {
    if (!self.backColor) {
        self.backColor = [UIColor redColor];
    }
    [self.backColor set]; //设置线条颜色
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    path.lineWidth = 1.8;
    
    path.lineCapStyle = kCGLineCapRound; //线条拐角
    path.lineJoinStyle = kCGLineJoinRound; //终点处理
    
    [path moveToPoint:CGPointMake(11.0, 10.0)];//起点
    
    // Draw the lines
    [path addLineToPoint:CGPointMake(1.0, 20.0)];
    [path addLineToPoint:CGPointMake(11.0, 30.0)];
    [path stroke];//Draws line 根据坐标点连线
    
    UILabel *backLabel = [[UILabel alloc] init];
    backLabel.text = @"返回";
    backLabel.frame = CGRectMake(13, 0, 40, 40);
    backLabel.font = [UIFont systemFontOfSize:17];
    backLabel.textColor = self.backColor;
    [self addSubview:backLabel];
}

UIView转换成Image的方法:

- (UIImage *)viewToImage:(UIView *)view {
    CGSize size = view.bounds.size;
    // 下面的方法:第一个参数表示区域大小;第二个参数表示是否是非透明的如果需要显示半透明效果,需要传NO,否则传YES;第三个参数是屏幕密度
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

Copyright © 2019- yule263.com 版权所有 湘ICP备2023023988号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务