【问题标题】:initWithCoder: Custom View - Determine view controller that is being instantiatedinitWithCoder:自定义视图 - 确定正在实例化的视图控制器
【发布时间】:2016-12-24 09:22:09
【问题描述】:

我已经准备了一个带有关联 Xib 文件的自定义 UIView 子类。在情节提要上,我放置了一个 UIView 并将它的类设置为我的自定义子类。在自定义视图的 initWithCoder: 方法中,我加载 xib 并初始化子视图。这很好用。

现在我想在其他地方使用相同的自定义视图,但我希望我的子视图的布局有所不同。我想在同一个 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;
}

是否有任何方法可以访问有关正在实例化此自定义视图的视图控制器的信息?

【问题讨论】:

    标签: ios objective-c storyboard xib initwithcoder


    【解决方案1】:

    是的,有一种方法,放置两个视图并将两个视图的标签设置为不同的,比如故事板中的 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 视图将被您的第二个视图替换。

    构建、运行和享受!!!

    【讨论】:

      猜你喜欢
      • 2013-08-05
      • 1970-01-01
      • 1970-01-01
      • 2016-09-27
      • 2015-07-20
      • 2011-05-15
      • 1970-01-01
      • 2015-08-11
      相关资源
      最近更新 更多