Использование isKindOfClass: я не понимаю, почему этот код ведет себя таким образом - программирование
Подтвердить что ты не робот

Использование isKindOfClass: я не понимаю, почему этот код ведет себя таким образом

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

Я ожидал, что вывод будет "element" - это UIImageView, но на самом деле элемент НЕ является UIImageView. Почему? Это не то, что есть другие подзапросы. Есть только один. Кроме того, при запуске изображение отображается на 100 100, а не 500 500, как ожидалось.

4b9b3361

Ответ 1

Ваш чек неверен. Вы должны вызвать isKindOfClass: для объекта, а не для класса объекта.

[element isKindOfClass:[UIImageView class]]

Ответ 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");
    }
}