使用XIB自定义UIView:
01:新建一个UIView继承自UIView。
02:新建一个xib文件,文件必须和上一步的自定义的UIView的名字一样。
03:在xib上添加各类控件。
重点:如何在其他ViewController中使用自定义的View
04:nib加载这个View
NSArray *nib = [[NSBundlemainBundle]loadNibNamed:@"AZDetailView"owner:selfoptions:nil];
AZDetailView *deataiView=[nib objectAtIndex:0];
得到这个自定义的View
推荐将其写在自定义View的对外接口中,使用类方法创建
+(LKTextView *)instanceTextView
{
NSArray* nibView = [[NSBundle mainBundle] loadNibNamed:@"LKTextView" owner:nil options:nil];
return [nibView objectAtIndex:0];
}
这样在其他页面创建时,也可以像普通控件一样创建。
接下来是填充这个视图。有两种方式。
第一种使用单例,在awakeFromNib中做数据填充,这样做有一个优点:在视图创建完后,数据就会被填充。缺点就是:使用了单例模型,增加了内存开销。
第二种利用setter方法。在自定义的视图中,定义一个属性.(通常为模型),然后在.m文件中利用setter方法,完成对视图的填充。优点:不使用单例,节省内存开销。缺点:视图创建完后,直到调用setter方法,数据才会被填充到视图上。但是,我们可以在下载数据完后,在创建视图,然后调用setter方法。这样看起来还是相当快速的填充了数据
05:
第一种,填充数据
在 -(void)awakeFromNib 方法中写上加载nib时,做的一些数据填充。(使用单例,获取单例模型,然后填充数据)。
-(void)awakeFromNib
{
AZDetailMediaModel *detailMedia=[AZDetailMediaModel shareDetailMedia];
self.nameLabel.text=detailMedia.name;
[self.pic setImageWithURL:[NSURL URLWithString:detailMedia.picUrl]];
self.start.text=detailMedia.start;
self.dictro.text=detailMedia.dicetor;
self.actor.text=detailMedia.actor;
self.type.text=detailMedia.type;
self.time.text=detailMedia.time;
self.introLabel.text=detailMedia.intro;
}
第二种,填充数据
利用Setter方式。设置模型属性,在.m文件中的set方法里,对数据进行填充。
使用注意:创建视图完成后,必须调用setter方式才能填充数据
.h文件
#import <UIKit/UIKit.h>
#import "AZDateRecommendModel.h"
@interface AZDateRecommendView : UIView
@property (weak, nonatomic) IBOutlet UILabel *day;
@property (weak, nonatomic) IBOutlet UILabel *chinaDate;
@property (weak, nonatomic) IBOutlet UILabel *date;
@property (weak, nonatomic) IBOutlet UIImageView *luckImageView;
@property (nonatomic,strong)AZDateRecommendModel *model;
@end
#import "AZDateRecommendView.h"
@implementation AZDateRecommendView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
- (void)setModel:(AZDateRecommendModel *)model
{
self.day.text = [model.GregorianCalendar componentsSeparatedByString:@"-"].lastObject;
self.date.text = model.GregorianCalendar;
self.chinaDate.text = [NSString stringWithFormat:@"农历%@", model.LunarCalendar];
}
@end
使用方法
_dateRecommendView = [[NSBundle mainBundle] loadNibNamed:@"AZDateRecommendView" owner:self options:nil].lastObject;
_dateRecommendView.frame = CGRectMake(40, 74, 250, 100);
_dateRecommendView.backgroundColor = [UIColor redColor];
//省略下载数据,填充模型
//设置模型,调用setter方法
_dateRecommendView.model=model;
[self.view addSubview:_dateRecommendView];