iOS開發總結(A0) - 自訂UIView

來源:互聯網
上載者:User

標籤:

根據我淺薄的ios開發經驗,可以有以下方法添加custom uiview 的內容

1)draw

2)build in xib

3)add subviews

在custom uiview 的m檔案中,一般按照以下對uiview進行初始設定:

 1 -(void)awakeFromNib{ 2     [self setup]; 3 } 4 -(void)setup{ 5 //set up view   6 } 7 -(instancetype)initWithFrame:(CGRect)frame{ 8     self=[super initWithFrame:frame]; 9     if (self) {10         [self setup];11     }12     return self;13 }

setup 中一般要做的事情有:

- setBackgroundColor:

- setContentMode:

- setOpaque: (盡量設定為 yes)

- setTranslatesAutoresizingMaskIntoConstraints: (如果使用autolayout,設定為no,否則可能constraint可能會衝突)

 

 

以下說明這三種方式的基本做法

一、draw

重寫uiview 的

-(void)drawRect:(CGRect)rect{}

方法,在該方法中畫uiview 的內容。

-可以用UIBezierPath畫;

- 可以用CGContext 各種畫圖函數;

- 可以用uikit中各種控制項內建的draw方法畫

(如UIImage 的drawInRect:, NSAttributedString的drawInRect:)

- 當設定custom view 內容,位置相關的properties時,調用[self setNeedDisplay],系統會適時繪製

 

問題:drawRect:方法中能否使用 addSubview 方法? 

我的理解:最好不要使用,因為可能每次draw都要add subview,

 

問題:如何添加UIButton ?

我的理解:在setup中用addsubview 的方式添加button(不要設定frame,此時view的geometry未確定),用NSLayoutContraint 約束button 的位置,或者在drawInRect:中設定button的frame

 

問題:如何接受使用者的touch/ gesture

我的理解:在setup 中添加gesture,或者重寫以下方法處理使用者互動

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{}-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{}-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{}-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{}

 

注意:drawInRect:是在main queue 中進行的,如果drawInRect:很複雜,或者需要繪製很多view, app 可能會卡。

對於這種情況,考慮concurrently build interface(參考wwdc視頻,後續有隨筆專門總結如何?)

 

用draw 的方法添加view內容,代碼複雜,但可以做到真正的customization

 

二、load from nib

1)建立view nib 檔,在ib中拖拽添加view的內容(注意view 的class 為custom view 的class),並設定constraint(如何設定constraint,將另有隨筆總結)。

2)可用以下語句直接建立view

[[[NSBundle mainBundle]loadNibNamed:@"xib file name "                                  owner:nil                                options:nil] lastObject];

 

好處(前提是熟悉ib):

1.方便快速的新增內容、設定iboutlet 和ibaction、添加gesture等

2.便於 localization

3.便於設定constraint

 

三、add subviews

這種方法比較直接,在setup中增加subviews 就可以了(這裡不適合設定frame等geometry資訊),

但好像運行效率比較低

 

iOS開發總結(A0) - 自訂UIView

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.