以网格模式在 UIScrollView 中添加子视图
Posted
技术标签:
【中文标题】以网格模式在 UIScrollView 中添加子视图【英文标题】:Adding subviews in UIScrollView in a grid pattern 【发布时间】: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;
【问题讨论】:
【参考方案1】:我读对了吗?看起来您没有设置 blurbsPerRow
。这会使其默认为 0 吗?
【讨论】:
我很惊讶你没有得到除以零的错误。另外,您无需先初始化就使用它。以上是关于以网格模式在 UIScrollView 中添加子视图的主要内容,如果未能解决你的问题,请参考以下文章
以编程方式在 UIScrollview 中添加多个 UIImageview
如何在 UIScrollView 的末尾添加一个按钮以加载更多?