簡(jiǎn)介
@IBDesignable和@IBInspectable是iOS8的新特性,可以實(shí)時(shí)渲染在interface builder上,并且直接修改就能發(fā)生變化。
因?yàn)?code>UIView.layer.borderWidth、borderColor、cornerRadius這些屬性在xib上是不能直接設(shè)置的,但是@IBDesignable和@IBInspectable利用運(yùn)行時(shí)機(jī)制,可以把這些屬性映射到xib上,同時(shí)還可以映射自定義的屬性。
更底層的原理可以參考Nate Cook的文章
邊框button的例子
import UIKit
@IBDesignable //@IBDesignable關(guān)鍵字用來(lái)聲明一個(gè)類(lèi)是可以被設(shè)計(jì)的,可以實(shí)時(shí)渲染在interface builder 上
class BorderButton: UIButton {
//@IBInspectable關(guān)鍵字用來(lái)聲明一個(gè)屬性,可以在interface builder上修改該屬性,就可以實(shí)時(shí)渲染border的變化
@IBInspectable var borderColor: UIColor = UIColor.black {
didSet {
layer.borderColor = borderColor.cgColor
}
}
@IBInspectable var opacity: Float = 0.0 {
didSet {
layer.opacity = opacity
}
}
@IBInspectable var borderWidth: CGFloat = 0.0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable var cornerRadius: CGFloat = 0.0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
}
下面為xib上的示例圖,可以看到右邊直接顯示了我們?cè)贐orderButton類(lèi)中自定義的IBInspectable屬性,可以直接調(diào)整,就會(huì)實(shí)時(shí)渲染了

demo.png
View的陰影例子
import UIKit
@IBDesignable
class HeaderMiddleView: UIView {
@IBInspectable var shadowColor: UIColor = UIColor.black {
didSet {
layer.shadowColor = shadowColor.cgColor
}
}
@IBInspectable var shadowOpacity: Float = 0.0 {
didSet {
layer.shadowOpacity = shadowOpacity
}
}
@IBInspectable var shadowOffset: CGSize = CGSize.init(width: 0, height: -3) {
didSet {
layer.shadowOffset = shadowOffset
}
}
@IBInspectable var shadowRadius: CGFloat = 3.0 {
didSet {
layer.shadowRadius = shadowRadius
}
}
}