简体   繁体   中英

In ViewController.m, how can I access a property declared in ViewController.h by a string?

For example, I have, in my ViewController.h:

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

in my ViewController.m, I have:

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 = @"";"
}

I'm trying to iterate through all of the buttons, and change their text property. Basically, I'm unsure of how to make the above for loop do the equivalent of:

self.buttonA.text = @"";
self.buttonB.text = @"";
...
self.buttonZ.text = @"";

because I'm using a NSString 'nameOfButton' instead of the actual property name.

You can make an IBOutlet collection instead of multiple UIButton IBOutlets and loop over the buttons in your outlet collection. When you make the connection between the view and code you choose outlet collection in the dialog that pops open. (under connection)

Example: call your IBOutlet collection button list and loop over it:

for (UIButton *button in self.buttonList) {
    [button setTitle:@"text" forState:UIControlStateNormal];
}

PS: Remember to always use set title for state, .text doesn't work on buttons

您可以使用KVC(键值编码)来使用字符串提取属性,例如

UIButton *btn = (UIButton *)[self valueForKey@"buttonA"];

This will work for you

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];
}

The code makes all your buttons in this series to change there title to there outlet name.The code with that log is self explanatory

您可以在循环中使用KVC(键值编码):

[self setValue:@"" forKeyPath:[NSString stringWithFormat:@"%@.text", nameOfButton]];

You can iterate through all the buttons in self.view if they are added to the viewcontroller's view with the following

for (UIButton *button in self.view.subviews) {
// your code here

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM