我需要将UIButtons放在UIScrollView上。我拥有的代码有效,但是根据我拥有的dataItems的数量,间距不均匀。

有问题的代码段

CGRectMake(10, ((120 / (count + 1)) * (i + 1) * 3) ,300,50)


特别

((120 / (count + 1)) * (i + 1) * 3)


工作代码

int count = [dataItems count];  /*  not a specific value, can grow  */
for (int i = 0; i < count; i++) {
    UIButton* aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [aButton setTag:i];
    [aButton setFrame: CGRectMake(10,((120 / (count + 1)) * (i + 1) * 3) ,300,50) ];
    [aButton setTitle:[[dataItems objectAtIndex:i] objectForKey:@"Feed"] forState:UIControlStateNormal];
    [aButton addTarget:self action:@selector(viewCategories:) forControlEvents:UIControlEventTouchUpInside];
    [scroller addSubview:aButton];
}


屏幕截图

就间距而言,右侧的示例应类似于左侧的示例。 UIButtons坐在UIScrollView上,因此,如果UIScrollView更多,contentSizedataItems也应该增大,这样,如果有30+ dataItems,则按钮可以在屏幕外滚动。

最佳答案

听起来您需要设置大小和填充...

int count = [dataItems count];
CGFloat staticX = 10; // Static X for all buttons.
CGFloat staticWidth = 300; // Static Width for all Buttons.
CGFloat staticHeight = 50; // Static Height for all buttons.

CGFloat staticPadding = 10; // Padding to add between each button.

for (int i = 0; i < count; i++) {
    UIButton* aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [aButton setTag:i];
    //Calculate with the Static values.
    //I added one set of padding for the top. then multiplied padding plus height for the count.
    // 10 + 0 for the first
    // 10 + 60 for the second.
    // 10 + 120 for the third. and so on.
    [aButton setFrame: CGRectMake(10,(staticPadding + (i * (staticHeight + staticPadding)) ,staticWidth,staticHeight) ];
    [aButton setTitle:[[dataItems objectAtIndex:i] objectForKey:@"Feed"] forState:UIControlStateNormal];
    [aButton addTarget:self action:@selector(viewCategories:) forControlEvents:UIControlEventTouchUpInside];
    [scroller addSubview:aButton];
}


但是,如果您尝试获取按钮来执行这种行为。我倾向于同意其余的内容。您可以创建一个带有按钮的自定义单元格。

然后,您可以在表格要求按钮时加载该按钮单元。

并且,您可以将表绑定到[dataItems count],以获取所有项目的总数。

那么您唯一的计算就是在最初设置dataItems计数时设置像元高度。确保不要让它们太短。桌子将处理其余的事情。

07-28 00:04