Search code examples
iosuiviewuiviewcontrolleriboutlet

Why can't I change UIView Class of root View of a ViewController


If I start an Xcode program with a single view template, it will default to a VC and a View already setup as an IBOutlet in that VC so that I can access it using self.view in my View Controller.

Now, if I wanted to have a custom UIView (called NewView), I can add a UIView class file (.h/.m) in my project. Now my initial thought would then to go to the root "UIview" in storyboard and change its class to "NewView".

Assuming I have a public property in NewView called "myProperty", I should be able to access it from my VC using self.view.myProperty. That is not the case!

Are we saying that the only way to subclass a UIView is to add a UIView object in SB that is below the root UIView and then create an IBOutlet from the VC to that UIView? So what it then the use of that root UIView if I cannot use it.


Solution

  • It's not a matter of not being able to subclass UIView (as you have seen already), it's a matter of the compiler recognizing your subclass. self.view is declared as a pointer to a UIView object, not of your subclass, so you have to do a little extra work to access it's properties; namely: casting. To access "myProperty", use [(NewView*)self.view myProperty];. Simple as that.

    You have to cast as a sort of promise to the compiler that literally states "self.view has the class NewView, not what you think it is, so recognize it as such."

    As a side note, I would also make sure that the class of the root view in the XIB is set appropriately (meaning, it needs to be of class NewView, else when you try to message it, your cast will fail and return a UIView object, which does not respond to -myProperty, thus throwing a generic exception).