简体   繁体   English

在ViewController.m中,如何通过字符串访问ViewController.h中声明的属性?

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

For example, I have, in my ViewController.h: 例如,我在ViewController.h中:

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

in my ViewController.m, I have: 在我的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 = @"";"
}

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: 基本上,我不确定如何使上面的for循环做相当于:

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

because I'm using a NSString 'nameOfButton' instead of the actual property name. 因为我使用的是NSString'nameOfButton'而不是实际的属性名称。

You can make an IBOutlet collection instead of multiple UIButton IBOutlets and loop over the buttons in your outlet collection. 您可以创建一个IBOutlet集合而不是多个UIButton IBOutlet,并遍历您的outlet集合中的按钮。 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: 示例:调用您的IBOutlet集合按钮列表并循环遍历它:

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 PS:记住要始终使用set title for state,。text不能用于按钮

您可以使用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 如果使用以下内容将它们添加到viewcontroller的视图中,则可以遍历self.view中的所有按钮

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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