How to implement UIScrollView with Subviews from XIB's
Whats 开发者_开发问答the best way to add a UIView (from a xib) to a UIScrollView, in a grid format?
I have looked into AQGridView, but I am not sure where to start to create the custom views I need.
I'm assuming by grid you mean something like the home screen springboard, where each icon is a different view.
I'm also assuming you've instantiated the UIView in IB and have set up all the appropriate connections and have a pointer in your code.
Then in your controller that owns the UIScrollView, (and this is what I would do, and have done before), is loop through all of your UIViews (after you copy the template one created in the xib; again I'm assuming here because your question isn't very well defined), set their frame using some simple math, and then add them to the UIScrollView using addSubview. At the end make sure to set your contentSize of the UIScrollView to the appropriate value.
Here's an example:
-(void)displayNewView:(NewView *)newIcon {
//create view object
NewViewController *newVC = [[NewViewController alloc] init];
//modify the new UIView so it shows the correct state
newVC.networkHost = newIcon;
//add view object to screen
[self.scrollView addSubview:newVC.view];
//release a retain on the object
[newVC release];
//reposition the view object
newVC.view.frame = CGRectMake((self.viewsOnDisplay%3*104), (self.viewsOnDisplay/3*105+6), 106, 95);
//resize the view if necessary
self.scrollView.contentSize = CGSizeMake(320.0, (self.viewsOnDisplay/3*105+96+6));
}
In the line where the view is repositioned, theres sum math going on and rather than show you a bunch of symbols I've taken a line from one of my apps and I will tell you what each number means (they are all different so it's a convenient way to differentiate them):
3: number of views per row
104: horizontal spacing between views
105: vertical spacing between views
6: space at the very top of the UIScrollView (a header if u will)
106: view width
95: view height
Because this is a method which simply adds a single UIView to the screen, it accesses the local synthesized property self.viewsOnDisplay
to know how many views there are already displayed so it knows where to put the next one. If you were doing this as part of a for loop or something, this would simply be i
(or whatever the counter var is called). Keep in mind your counter should start at 0.
精彩评论