I am trying to create a grid view containing multipl开发者_StackOverflowe rows and columns of image views. Like a view of 4 rows and 4 columns with each cell containing an image view. Can any one please tell me the best approach for creating such view? Thanks and Best Regards...
I'd make a GridView object descending from UIView. This would have a numberOfColumns property and an items property :
@class GridView : UIView {
NSUInteger numberOfColumns;
NSArray *items;
}
@property (nonatomic, assign) NSUInteger numberOfColumns;
@property (nonatomic, copy) NSArray *items;
@end
The items array would contain the UIViews that you wanted to display inside your grid view.
Then, each time that the numberOfColumns property or the items property is set, you also call [self setNeedsLayout]; in their setter i.e. for the items property you'd remove the old ones, add the new ones and tell the framework you need to relayout
- (void)setItems:(NSArray *)value {
if (value != items) {
for (UIView *item in items)
[item removeFromSuperview];
[items release];
items = [value copy];
for (UIView *item in items)
[self addsubview:item];
[self setNeedsLayout];
}
}
Your layoutSubviews method would iterate through the items array and position them in the correct number of columns i.e. something like
- (void)layoutSubviews {
[super layoutSubviews];
CGFloat width = [slef frame].size.width / numberOfColumns;
CGFloat height = width;
CGFloat xoffset = 0;
CGFloat yoffset = 0;
for (UIBView *item in items) {
[item setFrame:CGRectMake(xoffset, yoffset, width, height)];
xoffset += width;
if (xoffset >= [self frame].size.width) {
xoffset = 0;
yoffset += height;
}
}
}
I've not tested that code but it should lay the items out in a grid where each item is square.
Hope that's a good starting point.
I did this by UITableView. I make a custom UITableViewCell, each cell contains 4 buttons for 4 columns and adjust each cell'height for 4 row per page.
精彩评论