Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
700 views
in Technique[技术] by (71.8m points)

ios - How do I subclass a variable with an IBOutlet?

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 the sublclass as well, but as an IBOutlet. How do I do this?

I added the IBOutlet of the same name, and added weak to both variable declarations. But I get an error about "Cannot override with a stored property".

How should I be doing this? And is it possible to not have to instantiate the superclass' version as I just want it for subclassing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...