raptor85 raptor85 - 2 years ago 284
Objective-C Question

how to add multiple buttons on scrollview

i want to add buttons dynamically along with the scrollview ,suppose there are like 100 buttons to be added on scrollview it would be humongous to add it on nib file ,so i want to know how to write the code , add buttons dynamically on top of image view on scrollview

Answer Source

What you need to do is create a loop, create UIButtons. Setup buttons & add them as subviews to UIScrollView. Code follows.

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)];

What i am basically doing here is having variables for X & Y co-ordinates. As I am looping through to create UIButtons am creating the appropriate CGRect struct to decide where to place the button in the UIScrollView. After adding that button to scrollView, change the X & Y values to where ever you want to place the next button.

At the end dont forget to set the ContentSize for scrollview so that it enables scrolling.

PS: All this code is typed free hand, might have small syntactical errors but the logic is solid.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download