自定义UI的基本结构
- .h文件
@protocol
TRIPHotelXXXViewDelegate <NSObject>
- (
void
)actionA;
@end
@interface
TRIPHotelXXXView : UIView
@property
(nonatomic,weak) id <TRIPHotelXXXViewDelegate> delegate;
+ (instancetype)xxxView:(NSDictionary *)info width:(CGFloat)width;
@end
|
- .m文件
@implementation
TRIPHotelXXXView{
// 类变量
}
- (
void
)dealloc{
// 内存释放
SafeSuperDealloc(
super
);
}
- (id)initWithFrame:(CGRect)frame{
self = [
super
initWithFrame:frame];
if
(self) {
// 变量初始化
}
return
self;
}
- (
void
)layoutSubviews{
[
super
layoutSubviews];
CGFloat y =
0.0
;
// 子View的布局,y动态调整
// 更新自定义UI的高度
CGRect rect = self.frame;
rect.size.height = y;
self.frame = rect;
}
+ (instancetype)xxxView:(NSDictionary *)info width:(CGFloat)width;{
// 用view的数据及父view的宽度定义并初始化一个UI
TRIPHotelXXXView *view = [[TRIPHotelXXXView alloc] initWithFrame:CGRectMake(
0
,
0
, width,
0
)];
[view updateViewWithInfo:info];
return
view;
}
- (
void
)updateViewWithInfo:(NSDictionary *)info{
// view本身的数据填充
// 重新布局子View
[self layoutSubviews];
}
#pragma mark - Action
- (
void
)onSomeActionHappened:(id)sender{
if
(_delegate && [_delegate respondsToSelector:
@selector
(actionA)]) {
[_delegate actionA];
}
}
|
结构分析
- 数据准备好之前view已从原父view移除,并置为nil,之后进行UI的定义、初始化、添加到父view
- 必要之时,可将updateViewWithInfo:方法作为外部接口,在数据更新后也更新view的布局
- 自定义view由众多子view组成,高度动态调整,但也可以在初始化的时候置为定值,然后在固定高度的view中布局子view
- 可扩展性较强,可随时更具需求调整子view及布局
- 向外部提供delegate接口,根据业务在外部执行相应的动作
- 结构清晰