@IBDesignable和@IBInspectable簡(jiǎn)單使用

簡(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
        }
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容