2016-08-17 83 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

是的,有两种方式,放置两个视图,并设置两个视图的标记不同,例如10和20在你想用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视图替换标签将通过你的第二个观点所取代。

建立,运行和享受!

相关问题