你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> ios中view和controller設計原則的小結

ios中view和controller設計原則的小結

編輯:IOS開發綜合

針對UIView和UIViewController的設計原則,當前個人的一些思考,小結一下。以後再刷新

是否把UIView作為獨立的類

我的想法是,如果該視圖只對當前的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;
}

如果view需要復用的話:

-(void) loadView
{
    CGRect screenSize = [[UIScreen mainScreen] bounds];
    YLSSimplePasswordView *passwordView = [[YLSSimplePasswordView alloc] initWithFrame:screenSize Delegate:self];
    self.view = passwordView;
}

View的布局和行為,應該由Controller控制

要想實現View的復用,必須把view的布局和行為委托給Controller控制

控制view的布局,一般是通過

- (id)initWithFrame:(CGRect)frame;

controller調用此方法創建view,傳CGRect作為參數,確定此view在整個頁面中的位置和尺寸。同時,自定義的view定義若干delegate method,由controller實現這些方法

一般來說,view不需要持有controller的引用,只需要持有protocol的引用就可以了

id myDelegate;

View內部推薦使用相對布局

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];

本文先簡單總結這麼多,感覺View的布局和自適應是最麻煩的,以後還需要多總結

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved