針對UIView和UIViewController的設計原則,當前個人的一些思考,小結一下。以後再刷新
我的想法是,如果該視圖只對當前的controller適用,那麼就沒有必要獨立成一個類;反之,如果是一個通用的控件,就有必要獨立出去實現復用
不復用的view,直接寫在controller的loadView方法裡就可以了:
-(void) loadView { UIView *rootview = [[UIView alloc] init]; UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame = CGRectMake(200, 200, 80, 80); [button setTitle:@"click" forState:UIControlStateNormal]; [button addTarget:self action:@selector(clicked) forControlEvents:UIControlEventTouchUpInside]; [rootview addSubview:button]; self.view = rootview; }
-(void) loadView { CGRect screenSize = [[UIScreen mainScreen] bounds]; YLSSimplePasswordView *passwordView = [[YLSSimplePasswordView alloc] initWithFrame:screenSize Delegate:self]; self.view = passwordView; }
要想實現View的復用,必須把view的布局和行為委托給Controller控制
控制view的布局,一般是通過
- (id)initWithFrame:(CGRect)frame;
一般來說,view不需要持有controller的引用,只需要持有protocol的引用就可以了
idmyDelegate;
view有2個property,frame和bounds,分別用來表示此view在super view中的坐標系,及自身的坐標系:
The frame rectangle, which describes the view’s location and size in its superview’s coordinate system.
The bounds rectangle, which describes the view’s location and size in its own coordinate system.
在實踐中發現,frame更好用一些。比如這個view
下方這些button,指定它們的位置時,如果直接設置它們的frame,則需要使用root view的坐標系統(因為其super view是root view),計算起來很不方便
更好的做法,是把它們放在一個容器view中,這時候設置frame,就是相對於容器view的坐標系,計算起來會容易很多:
UIView *buttonViews = [[UIView alloc] init];// 作為button的容器 buttonViews.frame = CGRectMake((width-300)/2, 180, 300, 410);// 自身的frame相對於root view計算 // button的frame相對於button容器計算 YLSPasswordButton *button1 = [[YLSPasswordButton alloc] initWithTitle:@"1" Value:@"1" Color:pointColor Origin:CGPointMake(0, 0) Delegate:self]; YLSPasswordButton *button2 = [[YLSPasswordButton alloc] initWithTitle:@"2" Value:@"2" Color:pointColor Origin:CGPointMake(110, 0) Delegate:self]; YLSPasswordButton *button3 = [[YLSPasswordButton alloc] initWithTitle:@"3" Value:@"3" Color:pointColor Origin:CGPointMake(220, 0) Delegate:self]; [buttonViews addSubview:button1]; [buttonViews addSubview:button2]; [buttonViews addSubview:button3]; [self addSubview:buttonViews];