【问题标题】:How do I load objects and set properties dynamically?如何动态加载对象和设置属性?
【发布时间】:2012-05-15 01:05:34
【问题描述】:

我有几个要动态管理的 UIImageView 实例。我想将每个加载到一个可变数组中,然后设置每个实例的 animationImages 属性。 我的问题:如何将 UIImageViews 加载到可变数组中,然后如何动态设置属性? 下面是我创建动画对象的方法:

for (int i = 1; i <= 20; i++) {[myAnimation addObject:[UIImage imageNamed: [NSString stringWithFormat:@"frame-%i.png", i]]]; }

这是我添加对象的方式(非动态):

NSMutableArray *collection = [[NSMutableArray alloc]initWithObjects:imageView1,imageView2,...nil];

我不确定如何设置属性。我认为它应该类似于以下内容:

for (id xxx in collection) {
    xxx.animationImages=someAnimation;      
}

【问题讨论】:

  • 你试过了吗?你就是这样做的。
  • 你试过什么?是的,它应该看起来与你最终得到的相似,但你实际尝试了什么?
  • 这就是我所拥有的:NSMutableArray *collection = [[NSMutableArray alloc]initWithObjects:imageView1,imageView2,imageView3,imageView4,imageView5,imageView6,imageView7,nil]; for (id xxx in collection) { xxx.animationImages=hopAnimation;错误消息:语义问题:在“const __strong id”类型的对象上找不到属性“animationImages”另外,我仍然不知道如何将图像动态加载到 MutableArray 中。

标签: objective-c ios dynamic


【解决方案1】:

只需在您这样使用的for 循环中的行前添加UIImageView *imageView = (UIImageView *) xxx;

for (id xxx in collection) {
// Here add the line    
xxx.animationImages=someAnimation;      
}

【讨论】:

  • 我试过了,但收到一条错误消息:语义问题:在“const __strong id”类型的对象上找不到属性“animationImages”
  • 好的,我会检查一下,因为这在我的一个项目中对我有用
  • 应该是:for (UIImageView * xxx in collection) { xxx.animationImages=someAnimation; }
【解决方案2】:

如果你想使用快速枚举 for 循环样式,你需要使用:

for (UIImageView * xxx in collection) {
    xxx.animationImages=someAnimation;      
}

根据您所做的,看起来您应该考虑将这些添加到一些包含视图中,并从管理视图中的适当layoutSubviews: 调用中将它们布置出来。你会在哪里做类似的事情(从包含你的图像视图的视图中):

for (UIImageView * view in [self subviews]) {
    // move the image view around as needed.
}

如果这与您尝试完成的内容一致,将提供更多详细信息,但仍不清楚您尝试使用此代码“管理”什么。

【讨论】: