开发中经常要修改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];
效果图:
备注:可以支持( 上 下 左 右 )任一个边框颜色的修改
如果觉得《【iOS开发】自定义UIView边框的颜色》对你有帮助,请点赞、收藏,并留下你的观点哦!