I have a specific method that accepts a UIView
object, and I want to pass objects to it that can be of one of two classes. So say it accepts a UIView
that represents an animal, I want to be able to pass a DogView
and a CatView
or other animal-type classes potentially.
Within that method I want to set the nameLabel
view, which all animals have. How do I set it up so I'd be able to do this?
My first reaction was to have a super class (such as AnimalView
) that has the nameLabel
variable on it, and then subclass it for each new animal. However, if I want the nameLabel
to be an outlet, it doesn't seem settable as I couldn't have the variable in every subclass to wire the view up to in IB.
I then tried a Protocol
, but that's not polymorphic and I wouldn't be able to access the nameLabel property through a generic superclass, could I? Unlike Objective-C I couldn't ask for a UIView <ProtocolName>
and it would then allow me to ask for it.
How should I be doing this? I just want to be able to pass different kind of objects and have it be compatible with Interface Builder. Should I be approaching it completely differently?
You can connect outlet of label
to different viewControllers
with your SuperClass
from story board if your different viewControlelrs
in storyboard reperset by Subclasses
(derived from SuperClass) names in storyboard.
1)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
2)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
3)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
Declare the IBOutlet
in a superclass
, AnimalView
. Then in Interface Builder, once you have set the custom UIView's
class in the Identity inspector to be DogView
, go to the Connections Inspector and your nameLabel
will be there.
@interface Parent : UIView
@property (nonatomic,weak) IBOutlet UILabel *nameLabel;
@end
@interface Child : Parent
@end