素材巴巴 > 程序开发 >

【iOS开发】自定义UIView边框的颜色

程序开发 2023-09-03 17:11:40

开发中经常要修改UIView某一个边框的颜色,特别是UITableView。核心代码如下:

- (void)setBorderWithView:(UIView *)view top:(BOOL)top left:(BOOL)left bottom:(BOOL)bottom right:(BOOL)right borderColor:(UIColor *)color borderWidth:(CGFloat)width
 {if (top){CALayer *layer = [CALayer layer];layer.frame = CGRectMake(0, 0, view.frame.size.width, width);layer.backgroundColor = color.CGColor;[view.layer addSublayer:layer];}if (left){CALayer *layer = [CALayer layer];layer.frame = CGRectMake(0, 0, width, view.frame.size.height);layer.backgroundColor = color.CGColor;[view.layer addSublayer:layer];}if (bottom){CALayer *layer = [CALayer layer];layer.frame = CGRectMake(0, view.frame.size.height - width, view.frame.size.width, width);layer.backgroundColor = color.CGColor;[view.layer addSublayer:layer];}if (right){CALayer *layer = [CALayer layer];layer.frame = CGRectMake(view.frame.size.width - width, 0, width, view.frame.size.height);layer.backgroundColor = color.CGColor;[view.layer addSublayer:layer];}}
示例代码:
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(150, 250, 100, 100)];[self setBorderWithView:view top:YES left:YES bottom:NO right:YES borderColor:[UIColor greenColor] borderWidth:4.0];[self.view addSubview:view];

效果图:

这里写图片描述

备注:可以支持( 上 下 左 右 )任一个边框颜色的修改


标签:

素材巴巴 Copyright © 2013-2021 http://www.sucaibaba.com/. Some Rights Reserved. 备案号:备案中。