Objective-c: 如何使用自动布局向 UIView 添加边框

Objective-c: How to add borders to a UIView with auto layout

如何在 objective-c 中使用自动布局时向 UIView 添加具有特定颜色和粗细的边框?

此函数将向 UIView 的任何边框添加具有特定颜色和粗细的边框

- (void)addBorder:(UIView *)view toEdge:(UIRectEdge)edge withColor:(UIColor *)color withThickness:(float)thickness{
    UIView *border = [UIView new];
    border.backgroundColor = color;
    [border setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin];
    switch (edge) {
        case UIRectEdgeTop:
            border.frame = CGRectMake(0, 0, view.frame.size.width, thickness);
            break;
        case UIRectEdgeBottom:
            border.frame = CGRectMake(0, view.frame.size.height - thickness, view.frame.size.width, thickness);
            break;
        case UIRectEdgeLeft:
            border.frame = CGRectMake(0, 0, thickness, view.frame.size.height);
            break;
        case UIRectEdgeRight:
            border.frame = CGRectMake(view.frame.size.width - thickness, 0, thickness, view.frame.size.height);
            break;
        default:
            break;
    }
    [view addSubview:border];
}

用法

[self addBorder:yourView toEdge:UIRectEdgeTop withColor:[UIColor greenColor] withThickness:3.0f];

希望大家好好利用。