自定義UI的基本結構

自定義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];
     }
}

結構分析

  1. 數據準備好以前view已從原父view移除,並置爲nil,以後進行UI的定義、初始化、添加到父view
  2. 必要之時,可將updateViewWithInfo:方法做爲外部接口,在數據更新後也更新view的佈局
  3. 自定義view由衆多子view組成,高度動態調整,但也能夠在初始化的時候置爲定值,而後在固定高度的view中佈局子view
  4. 可擴展性較強,可隨時更具需求調整子view及佈局
  5. 向外部提供delegate接口,根據業務在外部執行相應的動做
  6. 結構清晰
相關文章
相關標籤/搜索