【问题标题】:Using isKindOfClass: I don't understand why this code is behaving this way使用 isKindOfClass:我不明白为什么这段代码会这样
【发布时间】:2012-11-17 03:42:21
【问题描述】:
-(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。

【问题讨论】:

  • 我尝试简单地更改代码以使用UIImageView而不是id,结果是一样的。
  • id 可以作为参考。您缺少的是您以错误的方式调用 isKindOfClass 方法。检查我的答案。

标签: ios uiimageview nsarray


【解决方案1】:

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

[element isKindOfClass:[UIImageView class]]

【讨论】:

  • 谢谢!现在你提到它,这是显而易见的!我在调试器中检查它,调试器显示 UIImageView,这真的让我很沮丧。我只是在查看要调试的代码的错误部分。再次感谢。
  • 很明显,但方法的名称令人困惑。在英语中,“is”这个词意味着身份。我确定那是我偏离轨道的地方。如果你问我,方法名称应该是 -isInstanceOfClass:。
【解决方案2】:

试试下面的代码。

-(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");
    }
}

【讨论】:

  • 原来是我没投?
  • 没关系。那是行不通的。标签的想法可能不适用于我的项目,除非我对所有图像使用相同的标签。会有未知数量的生命周期未知的图像。
  • 我刚刚编辑了我的答案if ([view isKindOfClass:[UIImageView class]]) 立即查看。
  • 应该是if ([view isKindOfClass:[UIImageView class]]) 你的代码不会编译。
  • 所以在回答我自己关于选角的问题时,不。这很好,因为使用 isKindOfClass 的全部意义在于您可能不知道该类。
猜你喜欢
  • 2021-04-10
  • 2023-04-01
  • 1970-01-01
  • 2020-03-28
  • 2012-05-25
  • 2010-12-14
  • 2012-09-01
  • 2014-04-11
  • 1970-01-01
相关资源
最近更新 更多