简体   繁体   中英

Add a subview to a custom class UIViewController that loads from nib, in Storyboard

To clarify on this ridiculous title:

I'm using my own subclass of JSQMessagesViewController ( https://github.com/jessesquires/JSQMessagesViewController ) - let's call it ACMessagesViewController. I'm loading my ACMessagesViewController through storyboard, by setting the storyboard UIViewController's custom class to ACMessagesViewController. I am trying to add a subview to ACMessagesViewController's view through the storyboard.

JSQMessagesViewController loads from a nib. When I add a subview to ACMessagesViewController's view through storyboard, the view disappears. The subview seems to be adding to a view other than my ACMessagesViewController's self.view, and by the time the viewdidload scope runs through, the subview is gone.

My questions are: 1. What is the proper way to add a subview (through storyboard) to a custom class UIViewController, when the UIViewController loads from a nib? 2. What is happening in this view loading process? Why is my subview (added through storyboard) adding onto a view that is not the same self.view in my ACMessagesViewController?

Thanks in advance!

I think it's one of those "if you need to work around it, you're probably doing it wrong" scenarios you so often hit in iOS development. :-) Really, if you want the functionality the JSQMessagesViewController provides, you shouldn't need to add additional views. But if you must add views, the "right" way to do it is to add them as subviews of whatever self.view is after you call super in viewDidLoad. If you don't want to construct views programmatically, you can put them in a separate nib (instead of the storyboard) and manually load them.

(Note: this is assuming viewDidLoad is getting called. If it isn't, you might need to hook into some other method.)

I used @Anna's suggestion to add the view in viewDidLoad but you don't need to use a second Xib or design the view in code. What you need is:

A. Design your view in the your JSQMessagesViewController scene in the storyboard/xib file.

B. Create an outlet of the view you need to present.

C. In viewDidLoad add your view with view.addSubview(myView) (or [self.view addSubview:self.myView] for all the objc ones out there)

D. That's it!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM