How do I subclass a variable with an IBOutlet?

前端 未结 4 1125
陌清茗
陌清茗 2020-12-16 13:57

All descendants of my specific class are to have a UILabel instance variable. So in my parent class I have var label: UILabel. I want to have it in

4条回答
  •  轮回少年
    2020-12-16 14:14

    Agreed that the short answer is simply:

    "Just add the @IBOutlet modifier in the superclass."

    One note though: if you will be exposing the ViewController in which the @IBOutlet is defined via a framework (with Carthage), you will need to add the public attribute to the variable definition. EDIT: instead, use open access keyword`.

    Let's say you have a view controller CustomViewController subclassing UITableViewController, which you will build in the Carthage-delivered framework. Everything which should be accessible to the consumer application should be tagged public:

    public class CustomViewController: UIViewController {
    
        override public func viewDidLoad() {
            super.viewDidLoad()
        }
    
    @IBOutlet public var myBackgroundView: UIView!
    @IBOutlet public weak var myLabel: UILabel!
    

    The nice thing about this approach (and I'm totally on-board with this use case) is that you can do the IBOutlet mapping in Interface Builder on the superclass, then switch the class of the Scene to the subclass, while retaining all of the mappings.

    E.g.: SubclassedCustomViewController

    import UIKit
    import mymodule
    
    class SubclassedCustomViewController: CustomViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            myBackgroundView.backgroundColor = UIColor.blueColor()
            myLabel.text = "My special subclass text"
        }
    

提交回复
热议问题