相关疑难解决方法(0)

使用xib创建可重用的UIView(并从storyboard加载)

好的,StackOverflow上有很多关于此的帖子,但没有一个在解决方案上特别清楚.我想UIView用随附的xib文件创建一个自定义.要求是:

  • 没有单独的UIViewController- 一个完全独立的类
  • 类中的出口允许我设置/获取视图的属性

我目前的做法是:

  1. 覆盖 -(id)initWithFrame:

    -(id)initWithFrame:(CGRect)frame {
        self = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class])
                                              owner:self
                                            options:nil] objectAtIndex:0];
        self.frame = frame;
        return self;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. -(id)initWithFrame:在我的视图控制器中以编程方式实例化

    MyCustomView *myCustomView = [[MyCustomView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
    [self.view insertSubview:myCustomView atIndex:0];
    
    Run Code Online (Sandbox Code Playgroud)

这工作正常(虽然从来没有调用[super init],只是使用加载的笔尖的内容设置对象似乎有点怀疑 - 这里有建议添加一个子视图在这种情况下也工作正常).但是,我希望能够从故事板中实例化视图.所以我可以:

  1. UIView在故事板中放置父视图
  2. 将其自定义类设置为 MyCustomView
  3. 覆盖-(id)initWithCoder:- 我见过的代码最常适合以下模式:

    -(id)initWithCoder:(NSCoder *)aDecoder {
        self = [super initWithCoder:aDecoder];
        if (self) {
            [self initializeSubviews];
        }
        return self;
    }
    
    -(id)initWithFrame:(CGRect)frame {
        self = [super initWithFrame:frame]; …
    Run Code Online (Sandbox Code Playgroud)

objective-c storyboard uiview nib ios

79
推荐指数
5
解决办法
6万
查看次数

标签 统计

ios ×1

nib ×1

objective-c ×1

storyboard ×1

uiview ×1