How would I use polymorphism to allow a method to accept multiple classes, but with IBOutlets?

自闭症网瘾萝莉.ら 提交于 2019-12-06 16:48:13

问题


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?


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/25089654/how-would-i-use-polymorphism-to-allow-a-method-to-accept-multiple-classes-but-w

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!