0

在我的应用程序中,我有 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);
        }
    }
   }  

但它会显示所有具有标题的按钮。请帮助我在两个按钮中仅更改标题

4

3 回答 3

1

实现这一点的一种棘手方法是标记 UIButtons,如果您希望 button1 和 button2 标题相同,请提供button1.tag = 1button2.tag = 100ie button2.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];

 }
于 2012-11-01T07:05:30.467 回答
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];
于 2012-11-01T08:07:27.930 回答
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++;
}
于 2012-11-01T09:39:50.173 回答