例如,我的ViewController.h中有:

@property (weak, nonatomic) IBOutlet UIButton *buttonA;
....
@property (weak, nonatomic) IBOutlet UIButton *buttonZ;

在我的ViewController.m中,我有:
for (unichar ch = 'A'; ch <= 'Z'; ch++) {
    NSMutableString *nameOfButton = [[NSMutableString alloc] initWithString:@"button"];
    [nameOfButton appendString:[NSString stringWithCharacters:&ch length:1]];
    //Code equivalent to change "self.(nameOfButton).text = @"";"
}

我试图遍历所有按钮,并更改其text属性。基本上,我不确定如何使上述for循环等效于:
self.buttonA.text = @"";
self.buttonB.text = @"";
...
self.buttonZ.text = @"";

因为我使用的是NSString'nameOfButton'而不是实际的属性名称。

最佳答案

这对你有用

for (unichar ch = 'A'; ch <= 'Z'; ch++) {
    NSMutableString *nameOfButton = [[NSMutableString alloc] initWithString:@"button"];
    [nameOfButton appendString:[NSString stringWithCharacters:&ch length:1]];
    //Code equivalent to change "self.(nameOfButton).text = @"";"
    NSLog(@"%@",nameOfButton);


    UIButton *btn = (UIButton *)[self valueForKey:nameOfButton];
    [btn setTitle:nameOfButton forState:UIControlStateNormal];
}

该代码使本系列中的所有按钮都可以将标题更改为插座名称。带有该日志的代码不言自明

07-26 04:39