How could I make this work with UIScrollView?
I'm inserting dynamically anywhere from 1 to 300 buttons inside a UIScrollView(as subviews). Currently, the buttons line up nicely but is not scrolling as I'd like them to. It just scrolls horizontally without a paging effect. Ideally, they way I'd like it to work is:
- Display a max of 48 buttons per "page"
- When scrolling to the right, show next "page" with 48 additional buttons
My code:
-(void)populateScrollView:(NSMutableArray *)colors {
// Properties
NSInteger count = 0;
NSInteger rowsize = 48;
CGFloat pageNum = 6;
CGFloat pageWidth = scrollView.frame.size.width;
CGFloat pageHeight = scrollView.frame.size.height;
CGFloat visibleWidth = 465;
myButtons = [[NSMutableArray alloc]init];
// Clear the subviews if any
for (UIView *subview in scrollView.subviews) {
[subview removeFromSuperview];
}
for (Color *element in colors) {
// Set the button properties
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *image = [UIImage imageNamed:@"color_overlay.png"];
[button setImage:image forState:UIControlStateNormal];
[button setImage:image forState:UIControlStateHighlighted];
div_t temp = div(count, rowsize);
button.frame = CGRectMake(52 * temp.rem , 52*temp.quot, 52, 52);
button.tag = count++;
UIImage *effect = [UIImage imageNamed:element.image_resource];
effectImage = [[UIImageView alloc] initWithImage:effect];
effectImage.frame = CGRectMake(52 * temp.rem , 52*temp.quot, 52, 52);
// Color the graphic if color available. If not, load the image
unsigned result = 0;
if ([element.hex_value length] > 1){
NSScanner *scanner = [NSScanner scannerWithString:element.hex_value];
[scanner scanHexInt:&result];
button.backgroundColor = UIColorFromRGB(result);
}
开发者_JS百科 else {
effectImage.image = effect;
}
// Set actions for the color
[button addTarget:self action:@selector(changeGraphicColor:) forControlEvents:UIControlEventTouchUpInside];
[myButtons addObject:button];
for (UIButton *myButton in myButtons){
[scrollView insertSubview:effectImage atIndex:1];
[scrollView insertSubview:myButton atIndex:2];
}
}
// Set scrollView contentSize and create pages:
CGFloat leftShift=floor(((visibleWidth-pageWidth)/2)/pageWidth)*pageWidth;
CGFloat contentSizeReduction=2*leftShift;
scrollView.contentSize = CGSizeMake(pageNum*pageWidth-contentSizeReduction,pageHeight);
[myButtons removeAllObjects];
[myButtons release];
}
I'm thinking the way I'm adding the buttons won't allow me to implement what I am trying to accomplish. What do you guys think I'm doing wrong here?
Did you set scrollView.pagingEnabled to YES?
精彩评论