15
-(void)viewWillAppear:(BOOL)animated
{
   [super viewWillAppear:animated];
   UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
   imageView.image = [UIImage imageNamed:@"Sample.png"];
   [self.view addSubview:imageView];
   NSArray *subviews = [self.view subviews];
   for(id element in subviews) {
      if ([[element class] isKindOfClass:[UIImageView class]]) //check if the object is a UIImageView
      {
         NSLog(@"element is a UIImageView\n");
         [element setCenter:CGPointMake(500., 500.)];
      } else {
         NSLog(@"element is NOT a UIImageView\n");
      }
   }
}

我预计输出是“元素是 UIImageView,但它实际上元素不是 UIImageView。为什么?不是有其他子视图。只有一个。此外,运行时,图像显示在 100,100,而不是 500,500正如预期的那样。

4

2 回答 2

45

你的支票错了。您应该调用isKindOfClass:对象而不是对象类。

[element isKindOfClass:[UIImageView class]]
于 2012-11-29T05:40:08.097 回答
0

试试下面的代码。

-(void)viewWillAppear:(BOOL)animated
{
   [super viewWillAppear:animated];
   UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
   imageView.image = [UIImage imageNamed:@"Sample.png"];
   [self.view addSubview:imageView];
   NSArray *subviews = [self.view subviews];
   for(UIView *view in subviews) {
      if ([view isKindOfClass:[UIImageView class]]) //check if the object is a UIImageView
      {
         NSLog(@"element is a UIImageView\n");
         [element setCenter:CGPointMake(500., 500.)];
      } else {
         NSLog(@"element is NOT a UIImageView\n");
      }
   }
}

您还可以按标签值检查子视图:

initially set imageView.tag=101;  //anything you want

for(UIView *subview in [view subviews]) {
    if(subview.tag== 101)/*your subview tag value here*/
     {

 NSLog(@"element is a UIImageView\n");
    } else {
       NSLog(@"element is NOT a UIImageView\n");
    }
}
于 2012-11-29T05:36:38.763 回答