开发者

Showing buttons on the screen using a for-loop with Objective-C

I have a database full of words, and each word contains information. My job is to show the words on screen using buttons, and without using interface builder. I figured I could do this with a for loop, like this:

for (int i=0; i <=20; i++) {

    UIButton *word= [UIButton buttonWithTyp开发者_运维知识库e:UIButtonTypeRoundedRect];
    [word setTitle:@"Test" forState:UIControlStateNormal];
    [word setFrame:CGRectMake(0, 0, 100, 40)];
    [self.view addSubview:word];
}

this is all done in the viewDidLoad section. But when I run the program, only one button is showed, so how can I make it show all the 20 buttons? Thanks on forehand, Nicholas


It may be useful.

for (int i=0; i <=20; i++) 
    { 
        UIButton *word= [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [word setTitle:@"Test" forState:UIControlStateNormal]; 
        [word setFrame:CGRectMake(0, (i+1)*100, 100, 40)]; 
        [self.view addSubview:word]; 
    }


You should dynamically change the frame of the buttons added. The following code places the views horizontally.

float _width = 100;
float _x = i * _width;
[word setFrame:CGRectMake(_x, 100, _width, 40)];


Every time Button Frame is Similar .. so only 1 button is showe ..

Try like this

[word setFrame:CGRectMake(0+i*110, 0+i*50, 100, 40)];

or set frame as per your need


What you are doing here is adding all the 100 btns on the same frame. Instead of this, if you want to show all the 100 btns on the screen, you'll have to use two for loops.

for example, if you wanna show four btns in a single row then you should use,

 for(i = 0 ; i < 20 (i.e. no of elements in a single column) ; i++ )
 {
      for(j = 0; j < 4 (i.e. no of elements in a single row) ; j++)
      {
              UIButton *word= [UIButton buttonWithType:UIButtonTypeRoundedRect];
              [word setTitle:@"Test" forState:UIControlStateNormal]; 
              [word setFrame:CGRectMake(j*40, i*100, 100, 40)]; 
              [self.view addSubview:word]; 
      }
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜