One xib, multiple subclasses

I have one xib file for a custom UIView subclass. Works great. I can load the correct nib and instantiate my class and it contains all the routines that I added to the xib file.

However, I subclassed this view as well, but cannot figure out how to instantiate this class and make it use the xib file used by the parent class. Is it possible? I don't want to create a new xib file for my subclass as the hierarchy of views, subviews and GUI looks the same, it's just code that is different.

Can I download the nib and "connect" it to a different class than the one listed as "Custom class" in the xib settings? Or can I create a new instance of the view and tell it to use the xib of a specific name?

+3


source to share


1 answer


You can try to write something really weird with -awakeAfterUsingCoder:

to replace the created object, but this is really wobbly and some might fix it.

The fact is that the .xib file stores a set of serialized objects, when this set is loaded, information about each object, that is, its class, size, other attributes, parent object, constraints are also deserialized and applied. This way, the xib files save which class should receive +alloc

other messages as well, and therefore which objects will receive all the attributes via KVC ( -setValue:forKey:

). So, no, you cannot just set up some class to load some xib, because the xib file tells which class should be loaded.



As a soul, I suggest refactoring your code (for example), encapsulating the logic of the various subclasses into some other object. So, before you have multiple subclasses with different logic, then you have one class loaded from xib, but you have to set some object MyDifferentLogicVariant1Implamentor

to keep different logic for the "different" classes.

Superclass - Subclass1 - Subclass2
vs
Superclass.differentLogic = DifferentLogicImplementor1
Superclass.differentLogic = DifferentLogicImplementor2

      

+2


source







All Articles