LoginSignup
0
2

More than 5 years have passed since last update.

UILabel 角丸の枠線に対応する(IBDesignable/IBInspectableを活用)

Posted at

数ヶ月前に、字間に対応したUILabelの実装について書きましたが、今回はそれの延長です。
http://qiita.com/sutchan/items/5fb089fabfefdd0e821c

今回は、角丸の枠線を持った、UILabelを実装します。

スクリーンショット 2017-03-07 12.52.32.png

実装

まずは、UILabelを継承した独自クラスを実装します。(Extensionで実装できるかなと思ったけどだめだった)
なお、Swift 2.3の場合の実装です。他では試してません :bow:

import UIKit
@IBDesignable
class BorderLabel: UILabel {
    @IBInspectable var borderColor: UIColor = UIColor.blackColor() {
        didSet{
            layer.borderColor = borderColor.CGColor
        }
    }

    @IBInspectable var borderWidth: CGFloat = 1.0 {
        didSet{
            layer.borderWidth = borderWidth
        }
    }

    @IBInspectable var cornerRadius: CGFloat = 0.0 {
        didSet{
            layer.cornerRadius = cornerRadius
        }
    }
}

今回は、ボーダーの色、幅、角丸を、Interface Builderから指定できるようにしました。
なお、IBInspectableで色を指定する場合、型はUIColorです。borderColorに色を代入する際には、CGColorにする必要があるので注意です。

ボーダーを付けたいUILabelに、実装したクラスを指定

スクリーンショット 2017-03-07 12.48.42.png

Attributes inspectorで各値が指定できる

スクリーンショット 2017-03-07 12.38.22.png

完成!!

Interface Builderでも、指定した結果が確認できるから、実装しやすいですね!!

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2