How do I subclass a variable with an IBOutlet?

前端 未结 4 1123
陌清茗
陌清茗 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:11

    By doing so you are re-declaring the label property in a subclass. IBOutlet is just a compiler notion for working with the Interface Builder.

    In Swift stored properties can not be overridden or redeclared in a subclass. They can only be inherited.

    However you can override the getter and setter of a properties in subclasses to provide extra validations or functionalities. Refer to the Swift guide: override getter setter

    You need to declare your property in superClass with IBOutlet.

    Or you can make a different property in your subclass. As also there is no meaning if you are connecting your property in one of subclasses(super class may have other) and you are not providing this implementation to other subclasses of your superclass.

    EDIT: You can also set label outlet to two different viewControllersof your SuperClass from story board if you give Subclasses names in storyboard to different view Controllers.

    Just define

     class SuperClass{
         @IBOutlet weak var label: UILabel! = nil
    
     }
    

    SubClass1 repersent view controller1 in storyboard derived from SuperClass SubClass2 repersent another view controller2 in storyboard derived from SuperClass

    Than Go to Assistant Editor and open SuperClass one side and other side view controller1 and connect outlet from SuperClass to label in storyBoard in view controller1.Drag from SuperClass label to storyBoard in view controller1

    enter image description here

    Now again open SuperClass one side and other side view controller2 and connect outlet from SuperClass to label in storyBoard in view controller2.Drag from SuperClass label to storyBoard in view controller2

    If you click on SuperClass outlet than you will see two labels conneted to different viewControllers

提交回复
热议问题