SwiftでAuto Layout設定した直後に一部を角丸表示

Auto Layout後に一部を角丸表示

UIViewで一部を角丸にするにはUIBezierPathとCAShapeLayerでmaskを使用するとできますが、Auto Layout設定後にこの方をそのまま使うと角丸表示されません。例によって、view.layoutIfNeeded()を読んでやる必要があるようです。


一部を角丸にする方法の参考サイト:
cornerRadiusを片側だけ効かせる(UIViewの一部だけ角丸にする)
Rounded UIView using CALayers - only some corners - How?


swift-layout対応

この機能を使って、swift-layoutで角丸ができるようにしました。

//UIView生成
let view = UIView(frame: CGRect(x: 10, y: 50, width: 100, height: 100))
view.backgroundColor = UIColor.redColor()
self.view.addSubview(view)
        
//右上と左上を角丸に
Layout.roundRect(view, byRoundingCorners: (UIRectCorner.TopLeft | UIRectCorner.TopRight),cornerRadii:20)

とあるUIViewかそのサブクラスを角丸にしたい場合

let layout = Layout.registUIView(superview: self.view)
    .top(30).fromSuperviewTop()
    .left(50).fromSuperviewLeft()
    .width(100)
    .height(100)
    .backgroundColor(UIColor.redColor())
    .roundRect(byRoundingCorners: (UIRectCorner.TopLeft | UIRectCorner.TopRight), cornerRadii: 20)

全部Layoutクラスで書く場合


roundRectTop(20)


(UIRectCorner.TopLeft | UIRectCorner.TopRight)の代わりに、.roundRectTop(20)でも可能

let layout1 = Layout.registUILabel(superview: self.view)
    .top(30).fromSuperviewTop()
    .left(50).fromSuperviewLeft()
    .width(100)
    .height(100)
    .backgroundColor(UIColor.redColor())
    .text("Top")
    .roundRectTop(20)

let layout2 = Layout.registUILabel(superview: self.view)
    .top(10).fromBottom(layout1.view)
    .left(50).fromSuperviewLeft()
    .width(100)
    .height(100)
    .backgroundColor(UIColor.cyanColor())
    .text("Right")
    .roundRectRight(20)

let layout3 = Layout.registUILabel(superview: self.view)
    .top(30).fromSuperviewTop()
    .left(10).fromRight(layout1.view)
    .width(100)
    .height(100)
    .backgroundColor(UIColor.yellowColor())
    .text("Left")
    .roundRectLeft(20)

let layout4 = Layout.registUILabel(superview: self.view)
    .top(10).fromBottom(layout3.view)
    .left(10).fromRight(layout2.view)
    .width(100)
    .height(100)
    .backgroundColor(UIColor.greenColor())
    .text("Bottom")
    .roundRectBottom(20)

let layout5 = Layout.regist(Layout.createCharWrappingLabel("TopLeft\nBottomRight"), superview: self.view)
    .top(10).fromBottom(layout2.view)
    .left(50).fromSuperviewLeft()
    .width(100)
    .height(100)
    .backgroundColor(UIColor.grayColor())
    .roundRect(byRoundingCorners: (UIRectCorner.TopLeft | UIRectCorner.BottomRight), cornerRadii: 20)