问题描述
这是一个我知道可以简化的基本示例,但为了测试,我想以这种方式做到这一点。我想根据附加字符串设置变量(变量cam0和pos1已在类中声明)。附加字符串本质上是一个索引,我将迭代循环将摄像机(cam0,cam1 ..)分配到不同的位置(pos0,pos1 ..)。
This is a basic example that I know can be simplified, but for testing sake, I would like to do this in such a way. I want to set a variable based on an appending string (the variables "cam0" and "pos1" are already declared in the class). The appending string would essentially be an index, and i would iterate through a loop to assign cameras (cam0, cam1..) to different positions (pos0, pos1..).
cam0定义为UIImageView
pos1定义为CGRect
cam0 is defined as an UIImageView
pos1 is defined as a CGRect
这适用于名为coverIndex的NSString变量:
This works for a NSString Variable named coverIndex:
NSString* text = [[NSString alloc] initWithString:@""];
NSLog(@"%@",(NSString *)[self performSelector:NSSelectorFromString([text stringByAppendingString:@"coverIndex"])]);
我为coverIndex设置的正确字符串已记录到控制台。
The correct string that I set for coverIndex was logged to the Console.
现在回到我的UIImageView和CGRect。我想要这个。
Now back to my UIImageView and CGRect. I want this to work.
NSString* camText = [[NSString alloc] initWithString:@"cam"];
NSString* posText = [[NSString alloc] initWithString:@"pos"];
[(UIImageView *)[self performSelector:NSSelectorFromString([camText stringByAppendingString:@"0"])] setFrame:(CGRect)[self performSelector:NSSelectorFromString([posText stringByAppendingString:@"1"])]];
我的错误是请求转换为非标量类型
My error is "Conversion to non-scalar type requested"
这是我发现做这种事情的唯一方法(并让NSLog工作),但我仍然相信有一种更简单的方法。
This is the only way I found to do this sort of thing (and get the NSLog to work), but I still believe there is an easier way.
非常感谢你的帮助:)
推荐答案
使用,这是一项令人惊叹的技术,可以满足您的需求:
Use KVC, it's an amazing piece of technology that will do just what you want:
for (int index = 0; index < LIMIT; index++) {
NSString *posName = [NSString stringWithFormat:@"pos%d", index];
CGRect pos = [[self valueForKey:posName] CGRectValue];
NSString *camName = [NSString stringWithFormat:@"cam%d", index];
UIImageView *cam = [self valueForKey:camName];
cam.frame = pos;
}
这篇关于使用表示变量名称的String来设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!