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

开发中经常要修改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边框的颜色_第1张图片

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

你可能感兴趣的:(Objective-C)