2012-11-29 3 views
14
-(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 아닙니다 사실의 그것은 아니다 왜 다른이 있다는 것을 .. 실행할 때 파단 하나가 또한, 이미지는 예상대로되지 500500, 100100에 표시됩니다isKindOfClass 사용 :.?이 코드는이 방법

+0

id 대신 UIImageView를 사용하도록 코드를 변경해 보았습니다. 그 결과는 동일했습니다. –

+1

id를 참조로 사용할 수 있습니다. 당신이 놓치고있는 것은 잘못된 방법으로 isKindOfClass 메서드를 호출하고 있다는 것입니다. 내 대답을 확인해. –

답변

44

수표가 잘못되었습니다. 오브젝트의 클래스가 아닌 isKindOfClass:을 오브젝트에 호출해야합니다.

[element isKindOfClass:[UIImageView class]] 
+0

+1. 이것이 바로 문제입니다. – iDev

+0

감사합니다! 이제는 언급 했으니 분명합니다! 디버거에서 그것을 검사하고 있었고 디버거가 UIImageView를 보여주었습니다. 정말 힘들었습니다. 디버깅 할 코드의 잘못된 부분을보고있었습니다. 다시 한번 감사드립니다. –

+0

분명하지만, 메서드 이름이 혼란 스럽습니다. 영어로, "is"라는 단어는 신원을 의미합니다. 내가 그 길에서 벗어난 곳이라고 확신한다. 당신이 나에게 묻는다면 메소드 이름은 -isInstanceOfClass :가되어야한다. –

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

내가 캐스팅하지 않았기 때문에 그런가? –

+0

신경 쓰지 마십시오. 그건 작동하지 않습니다. 모든 이미지에 동일한 태그를 사용하지 않으면 태그 아이디어가 내 프로젝트에서 작동하지 않습니다. 수명이 알려지지 않은 이미지는 알 수 없습니다. –

+0

i 그냥 내 대답'if ([view isKindOfClass : [UIImageView class]])'Check Now를 편집했습니다. –

관련 문제