Subviews for custom UIView with Nib (.xib) don't load?

别说谁变了你拦得住时间么 提交于 2019-12-11 01:18:06

问题


I am trying to create a custom UIView class with an associated Nib (.xib) file to help with layout and creation.

Right now, no subviews in my custom view appear, even though they exist in my nib file and are hooked up properly to my custom view class via IBOutlets.

I tried going through the following other answer: Load custom UIView with XIB from a View Controller's view using IB

and this one: How do I get a view in Interface Builder to load a custom view in another nib?

and this one: http://soulwithmobiletechnology.blogspot.com/2011/06/create-uiview-with-nib-file-in-xcode-4.html

but the method [[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil] seems to call -[initWithCoder:], leading to an infinite loop.

Please let me know what other details to include to help solve this bug!

UPDATE 1: Do I need to lay out my subviews via -[layoutSubviews]? Does my nib file actually not lay it out? If so, then what is the point of the nib file?


回答1:


Open any of your view controllers and paste this code into your viewDidAppear method:

NSArray * allTheViewsInMyNIB = [[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil]; // loading nib (might contain more than one view)
MyCustomView* problemView = allTheViewsInMyNIB[0]; // getting desired view
problemView.frame = CGRectMake(0,0,100,100); //setting the frame
[self.view addSubview:problemView]; // showing it to user

That's all you have to do, to present a view. If you want to interact with this view — you have to declare MyCustomView* problemView in your class' interface, not in the method.



来源:https://stackoverflow.com/questions/19137846/subviews-for-custom-uiview-with-nib-xib-dont-load

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