2016-08-17 8 views
1

관련 Xib 파일로 사용자 정의 UIView 하위 클래스를 준비했습니다. 스토리 보드에서 UIView를 배치하고 클래스를 내 사용자 정의 하위 클래스로 설정합니다. 사용자 정의보기의 initWithCoder : 메소드에서 xib를로드하고 하위보기를 초기화합니다. 이것은 잘 작동합니다.initWithCoder : 사용자 정의보기 - 인스턴스화중인보기 컨트롤러를 결정합니다.

다른 곳에서도 같은 사용자 정의보기를 사용하고 싶지만 내 하위보기의 레이아웃을 다르게 지정하고 싶습니다. 같은 Xib 파일에서 두 번째 사용자 지정보기 레이아웃을 만들고 내보기 컨트롤러에 사용자 지정보기가 포함되어 있는지에 따라 올바른보기를로드하고 싶습니다. 논리의 내 서브 뷰의 모든 모두가 같은 단지 레이아웃이 다른 때문에, 나는 이런 식으로 뭔가를 찾고 있어요 :

-(id)initWithCoder:(NSCoder *)aDecoder{ 
    if (self = [super initWithCoder:aDecoder]) { 
     if (self.subviews.count == 0) { 
      UINib *nib = [UINib nibWithNibName:NSStringFromClass([self class]) bundle:nil]; 
      UIView *subview; 
      if ([/*instantiating VC isKindOfClass:viewController1.class]*/) { 
       subview = [[nib instantiateWithOwner:self options:nil] objectAtIndex:0]; 
      } 
      else if ([/*instantiating VC isKindOfClass:viewController2.class]*/) { 
       subview = [[nib instantiateWithOwner:self options:nil] objectAtIndex:1]; 
      } 
      subview.frame = CGRectMake(0, 0, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame)); 
      subview.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; 
      [self addSubview: subview]; 
     } 
    } 
    return self; 
} 

은 인스턴스화되는 뷰 컨트롤러에 대한 정보에 액세스 할 수있는 방법이 있습니까 이 사용자 정의보기?

답변

0

예 방법이 있습니다. 두 개의 뷰를 배치하고 UIView 하위 클래스로 설정하려는 사용자 정의 클래스가있는 스토리 보드에서 두 개의 뷰 태그를 다르게 설정하십시오.

는 그런 다음 UIView 하위에서이 작업을 수행 :

-(id)initWithCoder:(NSCoder *)aDecoder { 

if (self = [super initWithCoder:aDecoder]) { 

    if (self.subviews.count == 0) { 

     UINib *nib = [UINib nibWithNibName:NSStringFromClass([self class]) bundle:nil]; 
     UIView *subview; 
     if (self.tag == 10) { 
      subview = [[nib instantiateWithOwner:self options:nil] objectAtIndex:0]; 
     } 
     else if (self.tag == 20) { 
      subview = [[nib instantiateWithOwner:self options:nil] objectAtIndex:1]; 
     } 

     subview.frame = CGRectMake(0, 0, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame)); 
     subview.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; 
     [self addSubview: subview]; 
    } 


} 
return self; } 

스토리 보드에서 10도 첫 번째보기 및 스토리 보드에있는 태그 (20)보기로 대체됩니다 태그는 두 번째보기로 대체됩니다.

빌드, 실행 및 즐기십시오 !!!