Use a generic class as a custom view in Interface Builder

前端 未结 3 1880
故里飘歌
故里飘歌 2020-11-29 08:05

I have a custom subclass of UIButton:

import UIKit

@IBDesignable
class MyButton: UIButton {

    var array : [String]?

}

It is IBDesignab

3条回答
  •  醉酒成梦
    2020-11-29 08:55

    It is possible to use generic UIView in Interface Builder. Let's say you have:

    class A: UIView {}
    

    First you have to inherit your generic view to make it non-generic:

    class B: A {}
    

    Go ahead and use B class in Interface Builder.

    After it you can make @IBOutlet connection in your code:

    @IBOutlet var b: B
    

    It will produce error, so to get rid of it make it use UIView class instead, and downcast it like so:

    @IBOutlet var b: UIView
    
    var _b: B {
        b as! B
    }
    

    Done, now your _b variable is type of B, and it works.

提交回复
热议问题