Use a generic class as a custom view in Interface Builder

前端 未结 3 1857
故里飘歌
故里飘歌 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:58

    I had the same problem as first I wanted to use the following structure :

    import UIKit
    
    protocol MyDataObjectProtocol{
       var name:String { get}
    }
    
    class MyObjectTypeOne:MyDataObjectProtocol{
        var name:String { get { return "object1"}}
    }
    
    class MyObjectTypeTwo:MyDataObjectProtocol{
        var name:String { get { return "object2"}}
    }
    
    class SpecializedTableViewControllerOne: GenericTableViewController {
    }
    
    class SpecializedTableViewControllerTwo: GenericTableViewController {
    }
    
    class GenericTableViewController: UITableViewController {
        // some common code I don't want to be duplicated in 
        // SpecializedTableViewControllerOne and SpecializedTableViewControllerTwo
        // and that uses object of type MyDataObjectProtocol.
    }
    

    But as explained in the previous answer, this is not possible. So I managed to work it around with the following code :

    import UIKit
    
    protocol MyDataObjectProtocol{
        var name:String { get}
    }
    
    class MyObjectTypeOne:MyDataObjectProtocol{
        var name:String { get { return "object1"}}
    }
    
    class MyObjectTypeTwo:MyDataObjectProtocol{
        var name:String { get { return "object2"}}
    }
    
    class SpecializedTableViewControllerOne: GenericTableViewController {
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            super.object = MyObjectTypeOne()
        }
    }
    
    class SpecializedTableViewControllerTwo: GenericTableViewController {
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            super.object = MyObjectTypeTwo()
        }
    }
    
    class GenericTableViewController : UITableViewController {
        var object : MyDataObjectProtocol?
    
        @IBOutlet weak var label: UILabel!
    
        override func viewDidLoad() {
            label.text = object?.name
        }
    
    
        // some common code I don't want to be duplicated in 
        // SpecializedTableViewControllerOne and SpecializedTableViewControllerTwo
        // and that uses object of type MyDataObjectProtocol.
    }
    

    Now my label outlet displays "object1" when I link the SpecializedTableViewControllerOne as a custom class of my view controller in the storyboard and "object2" if I link to SpecializedTableViewControllerTwo

提交回复
热议问题