美文网首页
iOS开发之多XIB之间相互关联

iOS开发之多XIB之间相互关联

作者: KnowWhy | 来源:发表于2017-05-23 10:21 被阅读0次

    1. 直接加载xib中的UIView

    创建一个View1.xib

    直接加载Xib中view

    获取View1代码:

    NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"View1"
                                                   owner:nil
                                                 options:nil];
    UIView *view1 = [views lastObject];
    

    2. 通过Owner建立变量关联

    File's Owner为NSObject类型,可以使用UIViewController,也可一创建一个继承NSObject的子类ViewFileOwner,以创建ViewFileOwner为例。

    ViewFileOnwer中声明IBOutLet的关联变量view

    #import <Foundation/Foundation.h>
    #import <UIKit/UIKit.h>
    
    @interface ViewFileOwner : NSObject
    
    @property (weak, nonatomic) IBOutlet UIView *view;
    + (id)viewFromNibNamed:(NSString *)nibName;
    
    @end
    
    #import "ViewFileOwner.h"
    
    @implementation ViewFileOwner
    
    + (id)viewFromNibNamed:(NSString *)nibName
    {
        ViewFileOwner *fileOwner = [ViewFileOwner new];
        [[NSBundle mainBundle] loadNibNamed:nibName
                                      owner:fileOwner
                                    options:nil];
        return fileOwner.view;
    }
    
    @end
    

    创建一个YZOwnerView.xib,File's Owner设为ViewFileOnwer,并建立关联,如下:

    建立File's Owner关联

    获取Xib View代码:

    ViewFileOwner *fileOwner = [ViewFileOwner new];
    [[NSBundle mainBundle] loadNibNamed:@"YZOwnerView"
                                  owner:fileOwner
                                options:nil];
    UIView *view = fileOwner.view;
    

    可以建立UIView的Category,封装方法,简化添加代码

    #import <UIKit/UIKit.h>
    
    @interface UIView (XibHelper)
    + (id)loadFromNibName:(NSString *)nibName;
    + (id)loadFromNib;
    
    @end
    
    #import "UIView+XibHelper.h"
    #import "ViewFileOwner.h"
    
    @implementation UIView (XibHelper)
    
    + (id)loadFromNibName:(NSString *)nibName
    {
        return [ViewFileOwner viewFromNibNamed:nibName];
    }
    
    + (id)loadFromNib
    {
        return [[self class] loadFromNibName:NSStringFromClass([self class])];
    }
    
    @end
    

    可直接这样调用:UIView *view = [UIView loadFromNibName:@"YZOwnerView"];

    如果建立UIView的子类YZView关联了Xib中View,可直接调用:YZView *view = [YZView loadFromNib];

    建立File's Owner关联
    UIView子类关联

    参考文章:iOS开发之多XIB之间相互关联

    相关文章

      网友评论

          本文标题:iOS开发之多XIB之间相互关联

          本文链接:https://www.haomeiwen.com/subject/ioswxxtx.html