如何在uibutton中分配标题两次

时间:2012-11-01 06:50:19

标签: iphone ios uibutton nsmutablearray

在我的应用程序中,我有10个UIButton个,以及一个包含5个文本值的数组。我想将每个值分配两次到10个按钮。我的代码

NSString *name;
int value = rand() % ([texts count] -1) ;
for(UIView *view in self.view.subviews)
{
    if([view isKindOfClass:[UIButton class]])
    {
        UIButton *button = (UIButton *)view;
        if(button.tag == 1||button.tag == 2||button.tag == 3||button.tag == 4||button.tag == 5||button.tag == 6||button.tag == 7||button.tag == 8||button.tag == 9||button.tag == 10||button.tag == 11||button.tag == 12||button.tag == 13||button.tag == 14||button.tag == 15||button.tag == 16||button.tag == 17||button.tag == 18||button.tag == 19||button.tag == 20)
        {
             name=[NSString stringWithFormat:@"%@",[texts objectAtIndex:value]];
            [button setTitle:name forState:UIControlStateNormal];
            NSLog(@"current  name :%@",name);
        }
    }
   }  

但它将所有按钮都设置为titile.Please帮我改成只有两个按钮的标题

3 个答案:

答案 0 :(得分:1)

实现此操作的一个棘手方法是标记UIButtons,如果您希望button1和button2标题相同,请提供button1.tag = 1button2.tag = 100button2.tag = button1.tag * 100(不要启动0为标签为0是self.view的保留标签。。这可以通过XIB或以编程方式完成。进一步执行以下

for (int i = 0 ;i < [array count] ; i++) {
int myTag = i + 1;

UIButton *button1 = [self.view viewWithTag:myTag];
    [button1 setTitle:[array objectAtIndex:i] forState:UIControlStateNormal];

UIButton *button2 = [self.view viewWithTag:myTag * 100];
    [button2 setTitle:[array objectAtIndex:i] forState:UIControlStateNormal];

 }

答案 1 :(得分:0)

NSArray *texts = [[NSArray alloc] initWithObjects:@"string 1",@"string 2",@"string 3",@"string 4",@"string 5",nil];
NSArray *buttons = [self.view subviews];
int t=0;
for (int i=0; i<[buttons count]; i++) {
    id view = [buttons objectAtIndex:i];
    if ([view isKindOfClass:[UIButton class]]) {
        UIButton *button = (UIButton *)view;
        [button setTitle:[texts objectAtIndex:t/2] forState:UIControlStateNormal];
        t++;
    }
}
[texts release];

答案 2 :(得分:0)

我只是修改你的代码,如果还有任何问题,可以帮助你,让我知道

谢谢

int i=1; 
int value = rand() % ([texts count] -1) ;
for(UIView *view in self.view.subviews)
{
    if([view isKindOfClass:[UIButton class]])
    {   

if(button.tag == 1||button.tag == 2||button.tag == 3||button.tag == 4||button.tag == 5||button.tag == 6||button.tag == 7||button.tag == 8||button.tag == 9||button.tag == 10||button.tag == 11||button.tag == 12||button.tag == 13||button.tag == 14||button.tag == 15||button.tag == 16||button.tag == 17||button.tag == 18||button.tag == 19||button.tag == 20)
    {
      int myTag= i+1;  
      UIButton *button1 = [self.view viewWithTag:myTag]; 
      name=[NSString stringWithFormat:@"%@",[texts objectAtIndex:value]];
       [button1 setTitle:name forState:UIControlStateNormal];
        NSLog(@"current  name :%@",name);
    }
     i++;
}