使用NIB文件創建UIVEW

使用NIB文件創建UIVEW

(1)之前使用NIB來創建UIVIEW的話,一般是創建一個UIVIEW,然後再創建一個NIB文件,將其"show the identity inspector"->"custom class"更改成自己創建的那個類名,讓NIB文件和.h .m文件建立起關係,然後就可以以拖線的方式對NIB文件上的控件建立屬性了,

其他方法是:(其實就是通過NSBundle mainBundle是通過加載XIB文件) 

//創建與使用
MyView *testView = [[[NSBundle mainBundle]loadNibNamed:@"MyView" owner:self options:nil]firstObject];
testView.myImageView.image = [UIImage imageNamed:@"animation.gif"];//支持GIF格式的,圖片不會動的
testView.myImageView.image = [UIImage imageNamed:@"test"];//可以只寫一個圖片名字,不寫後綴名也行
testView.myImageView.image = [UIImage imageNamed:@"image.jpg"];//其他格式的得寫“圖片名+後綴名”
testView.myLabel.text = @"測試數據";
[self.view addSubview:testView];

(2) 利用代碼來創建,在initWithFrame方法裏將其加到self上(但是在使用的時候遇到兩個問題,第一個問題:這個類裏我還涉及到向服務器請求信息,當信息被請求下來的時候,需要更新頁面,但是卻更新不了,最後發現,應該取到那個視圖,view = [self viewWithTag:6666],更新那個上面的控件。第二個問題:添加不上去手勢,即使userInteractonEnabled=YES 也不會去執行那個手勢方法,很是納悶!)- (id)initWithFrame:(CGRect)frame

{
self = [super initWithFrame:frame];
if (self) {
UIView *view = [[[NSBundle mainBundle]loadNibNamed:@"VipView" owner:self options:nil]firstObject];

view.tag = 6666;
[self addSubview:view];
}
return self;
}

(3) 創建NIB基類(一種貌似很厲害的方法哦!)

大致的思路:創建一個父類,用於加載當前對象的XIB文件,當創建子類對象時,先去執行父類裏的方法,先會加載對應的XIB文件,然後再其進行屬性設置。DEMO

父類

@interface GENibView : UIView
@end

#import "GENibView.h"
@implementation GENibView

- (id)initWithFrame:(CGRect)frame
{
self = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil] firstObject];

if (self) {

self.frame = frame;
}
return self;
}

@end

子類

.h

@interface VipView : GENibView
@property (copy, nonatomic) NSString *name;
@end

.m

#import "VipView.h"
@interface VipView ()
@property (strong, nonatomic) IBOutlet UILabel *nameLabel;
@end

@implementation VipView

- (id)initWithFrame:(CGRect)frame
{
self =
[super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}

-(void)setName:(NSString *)name{
_nameLabel.text = name;
}

-(NSString *)name{
return _nameLabel.text;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章