0

我有一个 for 循环设置按钮上的背景图像,基本上按钮是不同项目的缩略图预览并且不能静态设置,但是代码会发出警告,因为它会运行所有 UIView,然后调用 setBackgroundImage 不适用所有意见。警告是一种刺激,我明白它在抱怨什么,我该如何摆脱它?(我不想关闭警告,我想解决问题)

// For loop to set button images  
for (UIView *subview in [self.view subviews])  // Loop through all subviews  
{  
  // Look for the tagged buttons, only the 8 tagged buttons & within array bounds
  if((subview.tag >= 1) && (subview.tag <= 8) && (subview.tag < totalBundles))
  {
    // Retrieve item in array at position matching button tag (array is 0 indexed)
    NSDictionary *bundlesDataItem = [bundlesDataSource objectAtIndex:(subview.tag - 1)];

    // Set button background to thumbnail of current bundle
    NSString *picAddress = [NSString stringWithFormat:@"http://some.thing.com/data/images/%@/%@", [bundlesDataItem objectForKey:@"Nr"], [bundlesDataItem objectForKey:@"Thumb"]];
    NSURL *picURL = [NSURL URLWithString:picAddress];
    NSData *picData = [NSData dataWithContentsOfURL:picURL];
    // Warning is generated here
    [subview setBackgroundImage:[UIImage imageWithData:picData] forState:UIControlStateNormal];
  }
}
4

2 回答 2

0

您可以这样做:

for (id subview in [self.view subviews])

这样该id类型将停止任何类型检查...或检查对象是否响应选择器并像这样调用它:

if ([subview respondsToSelector:@selector(setBackgroundImage:forState:)]) {
    [subview performSelector:@selector(setBackgroundImage:forState:)
                  withObject:[UIImage imageWithData:picData]
                  withObject:UIControlStateNormal];
}

请注意,我从内存中编写了最后一部分。

于 2010-04-23T07:40:15.467 回答
0

有这么多假设的危险代码,但是......您最好先检查 UIView 的类,然后再向它发送 setBackgroundImage 消息,然后只需简单地转换您的 UIView 以删除警告:

if ([subview class] == [UIButton class]) {
    [((UIButton *)subview) setBackgroundImage:[UIImage imageWithData:picData] forState:UIControlStateNormal];
}
于 2010-04-23T07:44:43.513 回答