使用xib上的View的几种情况分析

2018-01-08  本文已影响0人  Qing学

使用xib搭建UI界面,因为所见即所得。搭建一些简单切无规律的UI比较方便。所以合理使用xib可以加快我们平时的开发进度。让我们更快更方便的完成项目中的工作。在这里整理了几种加载xib上View的方法。整理如下。
一、直接将xib搭建到storyBoard上
方法一;通过[[NSBundle mainBundle]loadNibNamed:@"XibView" owner:self options:nil];
1.创建xibView.xib和XibView.h和.m文件。将xibView.xib的file's Owner拖动到.m上


file's Own.png

.m文件内容如下

@property (strong, nonatomic) IBOutlet UIView *baseView;

@end

@implementation XibView

- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super initWithCoder:aDecoder]){
        [self initUI];
    }
    return self;
}

- (void)initUI{
    [[NSBundle mainBundle]loadNibNamed:@"XibView" owner:self options:nil];
    [self addSubview:self.baseView];
}

- (IBAction)btnClick:(id)sender {
    NSLog(@"按钮被点击了");
}

2.在StoryBoard上创建View。设置view的约束。并且将view的类型设置为XibView
方式二:
1.创建xibView.xib和XibView.h和.m文件将xib文件的placeHolder类型设置为xibView
.m文件代码如下

@interface XibSecond ()

@property (weak, nonatomic) IBOutlet UIButton *btnClick;

@end

@implementation XibSecond

- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super initWithCoder:aDecoder]){
        [self initUI];
    }
    return self;
}

- (IBAction)btnClick:(id)sender {
    NSLog(@"test");
}

- (void)initUI{
    XibSecond *seconView = [[[NSBundle mainBundle]loadNibNamed:@"XibSecond" owner:self options:nil]firstObject];
    [self addSubview:seconView];
}

方法三:通过XXNibBridge
1.导入#import <XXNibBridge.h>,同时让.h文件遵守<XXNibBridge>协议
2.将xib的customClass设置为XibThird


image.png

3.将stordBoard上的view的类型设置为XibThird

二、将xibView直接添加到视图上。
1.创建thirdViewManager工具类。创建类方法
thirdViewManager.h文件

#import <Foundation/Foundation.h>
#import "XibThird.h"

@interface BaseViewManager : NSObject

+ (XibThird *)createThirdView;

@end

thirdViewManager.m文件

#import "BaseViewManager.h"

@implementation BaseViewManager

+ (XibThird *)createThirdView{
    XibThird *thirdView = [[[NSBundle mainBundle]loadNibNamed:@"XibThird" owner:self options:nil]firstObject];
    return thirdView;
}

@end

将xib的customClass设置为XibThird
在controller的使用方法为

XibThird *thirdVeiw = [BaseViewManager createThirdView];
    [self.view addSubview:thirdVeiw];

然后可以将XibThird的action方法在XibThird.m文件中进行设置

2018-01-08 21:37:07.571626+0800 XibTest[7943:294468] click
2018-01-08 21:37:07.754162+0800 XibTest[7943:294468] click
2018-01-08 21:37:07.915496+0800 XibTest[7943:294468] click
2018-01-08 21:37:08.113700+0800 XibTest[7943:294468] click
2018-01-08 21:37:08.288262+0800 XibTest[7943:294468] click

可以看到xib上的按钮点击事件可以正常执行。

上一篇 下一篇

猜你喜欢

热点阅读