我怎样才能使用UIScrollView?

时间:2011-08-31 14:14:40

标签: ios ipad loops sdk uiscrollview

我在UIScrollView内部动态插入1到300个按钮(作为子视图)。目前,按钮很好地排列,但不是我想要的滚动。它只是水平滚动而没有分页效果。理想情况下,他们喜欢它的工作方式是:

  • 每个“页面”最多显示48个按钮
  • 向右滚动时,使用48个附加按钮显示下一个“页面”

我的代码:

-(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);
    }
    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];

}

我在想我添加按钮的方式不允许我实现我想要实现的目标。你们认为我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

您是否将scrollView.pagingEnabled设置为YES?