1. 程式人生 > >iOS 指定控制元件使用圓角屬性

iOS 指定控制元件使用圓角屬性

以Button為例
建立Button就不寫了

設定圓角通常用layer.cornerRadius,也就是像下面這樣
button.layer.masksToBounds = YES;
button.layer.cornerRadius = 4.;

但是UI也經常變化的,例如要設定成某個角為圓角,layer.cornerRadius就摸瞎了,畢竟這個屬性是通用全形的。
這裡就需要使用UIBezierPath去設定,具體如下:

typedef NS_OPTIONS(NSUInteger, UIRectCorner) {
    UIRectCornerTopLeft     = 1
<< 0, UIRectCornerTopRight = 1 << 1, UIRectCornerBottomLeft = 1 << 2, UIRectCornerBottomRight = 1 << 3, UIRectCornerAllCorners = ~0UL }; UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:button.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight) cornerRadii:CGSizeMake(4
, 4)]; CAShapeLayer *shapeLayer = [[CAShapeLayer alloc] init]; shapeLayer.frame = button.bounds; shapeLayer.path = bezierPath.CGPath; button.layer.mask = shapeLayer;

引數:UIRectCorner:意思就是表面的意思
typedef NS_OPTIONS(NSUInteger, UIRectCorner) {
UIRectCornerTopLeft = 1 << 0,
UIRectCornerTopRight = 1 << 1,
UIRectCornerBottomLeft = 1 << 2,
UIRectCornerBottomRight = 1 << 3,
UIRectCornerAllCorners = ~0UL
};