以网格模式在UIScrollView中添加子视图

时间:2011-01-16 05:57:21

标签: ipad ios uiviewcontroller uiscrollview grid

我正在向UIScrollView添加子视图(这是UIVewController),并且他们没有像他们想象的那样形成2 x 2网格。以下是我正在使用的一些代码:

-(void)layoutSubviews{

    BOOL blurbsHaveBorder = YES;

    int blurbCount = 3;
    int blurbsPerRow;

    int viewWidth = gridView.bounds.size.width;
    int viewHeight = gridView.bounds.size.height;

    int blurbWidth = 320;
    int blurbHeight = 320;

    int spaceWidth = round((viewWidth -blurbWidth * blurbsPerRow) / (blurbsPerRow + 1));
    int spaceHeight = spaceWidth;

    int rowCount = ceil(blurbCount / (float)blurbsPerRow);
    int rowHeight = blurbHeight + spaceHeight;


    if (blurbsPerRow < 1) blurbsPerRow = 1;


    NSInteger rowsPerView = viewHeight / rowHeight;
    NSInteger topRow = gridView.contentOffset.y / rowHeight;
    NSInteger bottomRow = topRow + rowsPerView;

    NSInteger startAtIndex = topRow * blurbsPerRow;
    NSInteger stopAtIndex = (bottomRow * blurbsPerRow) + blurbsPerRow;
    if (stopAtIndex > blurbCount) stopAtIndex = blurbCount;

    int x = spaceWidth;
    int y = spaceHeight + (topRow * rowHeight);

    int i;
    /*  add new subviews.  */ 
    for (int i = startAtIndex; i < stopAtIndex; i++) {
        if (i >= 0) {

            blurbItem = [[BlurbItem alloc] initWithFrame:CGRectMake(5,5,blurbWidth,blurbHeight) 
                                            andHasBorder:blurbsHaveBorder];

            [gridView addSubview:blurbItem.view];
            [blurbItem release];
        }   

    }

    /*  adjust the position.  */
    if ( (i+1) % blurbsPerRow == 0) {
        /*  start new row.  */
        x = spaceWidth;
        y += blurbHeight + spaceHeight;
    } else {
        x += blurbWidth + spaceWidth;
    }
}

1 个答案:

答案 0 :(得分:0)

我读到这个吗?看起来你没有设置blurbsPerRow。这会使它默认为0吗?