调用NSMutableArray Objective-C中UIButton对象的方法



我有一个名为buttons的数组,它由UIButton对象组成。我按如下方式填充它:

for (int i=0; i<self.numButtons; i++) {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"Title" forState:UIControlStateNormal];
    button.frame = CGRectMake(xCoord-40, y, 80, 20);
    [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [button setTag:i];
    [self.buttons addObject:button];
    [self.view addSubview:button];
    y+= 45;
}

这些按钮的操作是buttonAction。此操作旨在更改所选按钮的颜色。以下是我如何实现它:

-(void) buttonAction:(id)sender{
    int num = (int)[sender tag];
    [[self.buttons objectAtIndex:num] setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    NSLog(@"%@", [self.buttons objectAtIndex:buttonClicked].titleLabel.text);
}

结果是没有颜色变化。即使当我尝试NSLog按钮的标题时,它也会返回(null)。所以我的问题是如何解决这个问题,以及如何调用数组中对象的方法?如有任何帮助,我们将不胜感激。谢谢

所有证据都表明self.buttonsnil。你曾经初始化过它吗?

在某个地方你需要一条线路,比如:

self.buttons = [NSMutableArray array];

当然,您可以将sender参数用于buttonAction:方法:

- (void)buttonAction:(UIButton *)button {
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
}

注意参数的变化。

我喜欢这样做。别忘了使用IBAction。如果你决定使用笔尖或故事板,它会有所帮助。

-(IBAction) buttonAction:(id)sender{
    [((UIButton*)sender) setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]
    NSLog(@"%@", ((UIButton*)sender).titleLabel.text)
}

最新更新