【问题标题】:Adding subviews in UIScrollView in a grid pattern以网格模式在 UIScrollView 中添加子视图
【发布时间】:2011-01-16 05:57:21
【问题描述】:

我将子视图添加到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;
    }
}

【问题讨论】:

    标签: ipad ios uiviewcontroller uiscrollview grid


    【解决方案1】:

    我读对了吗?看起来您没有设置 blurbsPerRow。这会使其默认为 0 吗?

    【讨论】:

    • 我很惊讶你没有得到除以零的错误。另外,您无需先初始化就使用它。
    猜你喜欢
    • 2012-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-28
    • 2023-03-05
    • 2016-02-04
    • 1970-01-01
    相关资源
    最近更新 更多