使用xib搭建UI界面盗冷,因為所見即所得荔烧。搭建一些簡單切無規(guī)律的UI比較方便兑徘。所以合理使用xib可以加快我們平時的開發(fā)進(jìn)度刚盈。讓我們更快更方便的完成項目中的工作。在這里整理了幾種加載xib上View的方法挂脑。整理如下藕漱。
一欲侮、直接將xib搭建到storyBoard上
方法一;通過[[NSBundle mainBundle]loadNibNamed:@"XibView" owner:self options:nil];
1.創(chuàng)建xibView.xib和XibView.h和.m文件肋联。將xibView.xib的file's Owner拖動到.m上
.m文件內(nèi)容如下
@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上創(chuàng)建View威蕉。設(shè)置view的約束。并且將view的類型設(shè)置為XibView
方式二:
1.創(chuàng)建xibView.xib和XibView.h和.m文件將xib文件的placeHolder類型設(shè)置為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.導(dǎo)入#import <XXNibBridge.h>橄仍,同時讓.h文件遵守<XXNibBridge>協(xié)議
2.將xib的customClass設(shè)置為XibThird
3.將stordBoard上的view的類型設(shè)置為XibThird
二韧涨、將xibView直接添加到視圖上。
1.創(chuàng)建thirdViewManager工具類侮繁。創(chuàng)建類方法
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設(shè)置為XibThird
在controller的使用方法為
XibThird *thirdVeiw = [BaseViewManager createThirdView];
[self.view addSubview:thirdVeiw];
然后可以將XibThird的action方法在XibThird.m文件中進(jìn)行設(shè)置
-
(IBAction)btnClick:(id)sender {
NSLog(@"click");
}
顯示效果為
image.png
同時點擊按鈕效果為
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上的按鈕點擊事件可以正常執(zhí)行虑粥。