如何在scrollview上添加多个按钮

rap*_*r85 4 iphone objective-c uibutton uiscrollview ios

我想动态添加按钮和滚动视图,假设滚动视图上有100个按钮,将它添加到nib文件上是很大的,所以我想知道如何编写代码,动态添加按钮在scrollview上的图像视图

Sri*_*aju 7

你需要做的是创建一个循环,创建UIButtons.设置按钮并将其添加为子视图UIScrollView.代码如下.

NSUInteger i;
int xCoord=0;
int yCoord=0;
int buttonWidth=100;
int buttonHeight=50;
int buffer = 10;
for (i = 1; i <= 100; i++)
{
    UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
    aButton.frame     = CGRectMake(xCoord, yCoord,buttonWidth,buttonHeight );
    [aButton addTarget:self action:@selector(whatever:) forControlEvents:UIControlEventTouchUpInside];
    [scrollView addSubview:aButton];

    yCoord += buttonHeight + buffer;
}
[scrollView setContentSize:CGSizeMake(700, yCoord)];
Run Code Online (Sandbox Code Playgroud)

我在这里基本上做的是为X和Y坐标设置变量.当我循环创建UIButtons我创建适当的CGRect结构来决定将按钮放在哪里时UIScrollView.将该按钮添加到scrollView后,将X和Y值更改为您要放置下一个按钮的位置.

最后不要忘记设置ContentSize滚动视图,以便滚动.

PS:所有这些代码都是自由输入的,可能有小的语法错误,但逻辑是可靠的.