How to embed nibs programmatically?

烂漫一生 提交于 2019-12-11 03:05:54

问题


I have a UIViewController with an UIScrollView in it.

Then I created a new UIView subclass with some properties that I want to programmatically add in this UIScrollView until my data ends.

Something that should look like this picture:

I have read other topics that does that by creating a view and setting its class to the custom view subclass, but I want to do it programmatically and its not working.

how would I do that?


回答1:


From your image it looks like you're looking to load views from a nib and add them as subviews of your UIScrollView. To do this have a look at the UINib documentation.

You want to create your nib and set it's main view to be an instance of your UIView subclass then load the nib in viewDidLoad of your viewController, and add the nib's views as subivews of your scrollview (which I'm assuming is a subview of your viewController's view).

You can instantiate a nib with instantiateWithOwner:options:.

This method unarchives each object, initializes it, sets its properties to their configured values, and reestablishes any connections to other objects

To get the array of views from a nib you do something similar to:

UINib *myNib = [UINib nibWithNibName:@"myNib" bundle:[NSBundle mainBundle]];
NSArray *viewsFromNib = [myNib instantiateWithOwner:nil options:nil];

I'll assume we're inside a UIViewController and we're somewhere in (or after) viewDidLoad. You would then use the array from above and add the views as subviews of your scrollview. You may need to set the frames of these views to place them properly, but that should be trivial.

UIView *aView = [viewsFromNib objectAtIndex:0];
[self.scrollView addSubview:aView];

I hope that sets you in the right direction.

Edit:

If you want more information you may need to read deeper into how nibs work to manage your expectation. Linked with the UINib documentation is the 'Resource Programming Guide' in particular the nib section




回答2:


André, this can be done with relative ease. make sure to import the class that you want to embed. then to create them with your normal

ClassName *subview=[[ClassName alloc]init]; 
[subview.view setFrame:CGRectMake(x,y,width,height)]; 
[self.view addSubview:subview.view]; 

which will add it to the x,y coordinates you specify with the size specified by your width, height. you can do this in the viewDidLoad or whenever you need them to be created.



来源:https://stackoverflow.com/questions/11836489/how-to-embed-nibs-programmatically

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