1. 程式人生 > 實用技巧 >Sagit.Framework For IOS 自動佈局教程:8、UI元素的型別轉換as

Sagit.Framework For IOS 自動佈局教程:8、UI元素的型別轉換as

前言:

在UI佈局的時候,返回的是UIView這個基型別,而設定屬性時,需要具體的型別,為了方面性連續性寫法,可以用asXXX轉換成具體型別。

型別轉換定義:

@interface UIView(STUIViewAs)
-(UISwitch*)asSwitch;
-(UIStepper*)asStepper;
-(UIProgressView*)asProgressView;
-(UILabel*)asLabel;
-(UIImageView*)asImageView;
-(UITextField*)asTextField;
-(UITextView*)asTextView;
-(UIButton*)asButton;
-(UIScrollView*)asScrollView; -(UITableView*)asTableView; -(UICollectionView*)asCollectionView; -(UIPickerView*)asPickerView; -(STView*)asSTView; -(UIView*)asBaseView; -(UIImage*)asImage; @end

說明:

1、新增具體UI:返回具體的UI型別。

[sagit addUIButton:@“name"] 

此時返回的是具體型別 UIButton。

這個時候,可以設定一些UIButton的相關屬性。

2、相對佈局時:返回的是UIView這個基型別。

[[sagit addUIButton:@“name"]  x:0 y:0]

如果此時對UIButton 進行寬高、XY座標、relate方法等佈局方式,則此時返回的是 UIView。

此時無法再進行UIButton的屬性設定。

-------------------------------------------------------------------------------------------------------------------------

3、因此佈局有幾種寫法:

1、先佈局,再通過block設定屬性:需要手工block中的UIView修改具體的型別:UIButton,一般個人只有在層級佈局時才使用。

[[sagit addUIButton:@“name"]  x:0 y:0] block^(UIButton*view){

    [view text:@"xxxx"];
}];

2、用asXXX屬性進行轉換【屬性少的時候,可以中間進行型別轉換使用,太長了就不好用了。】

[[[[sagit addUIButton:@“name"]  x:0 y:0] asUIButton] text:@"xxxx"];

3、先設定屬性、再佈局【屬性少的時候,這種寫法最簡短。】

[[[sagit addUIButton:@“name"] text:@"xxxx"] x:0 y:0] 

4、拆分兩種寫法:佈局1行、屬性1行。【屬性多的時候,拆成兩行是看起來最舒服的。】

[[sagit addUIButton:nil] width:20 height:20 x:0 y:0]
[STLastUIButton text:@"hello"];

通過STLastUIXXX型別,可以拿到剛新增的UI控制元件的具體型別。

總結:

程式碼的寫法是多種的,具體喜歡哪種,都可以,只要知道兩點:

1、涉及到佈局時返回的是基類:UIView。

2、看第1點。