這一部份為單純使用Code寫一個顯示的畫面的 Hello World共三篇,此為第二篇。    第一篇第三篇有關這個分類的說明

  


本節要學的事:

  1. UIColor 的設定
  2. UILabel 的其他常用 property
  3. UIButton 的生成與設定
在上一個 Hello World 中我們使用了 UILabel 並把它加入主要的 View 當中,但只設定了 text 與 frame,接下來我們要對UILabel 多做一些事,並另外多加一個 Button 在畫面中央。

如果我們用 XCode Help 文件去查 UILabel 這個 Class 的話,就可以看到其實可用的設定還很多,它的父 Class 可用的類別也很多,這次我們設幾個比較常用的:UIView 的 backgroundColor,UILabel 的 textColor 與 textAlignment。另外我們要加一個新的 UIButton 類別在畫面當中,做為下一個Hello World 的準備。

首先我們來看一下 UIView 的 backgroundColor 這個 property,它要求一個 UIColor 實體。 UIColor 有很多種方式生成,比如說基本的顏色來說,它提供了一堆 Class method 來生成,我們可以用 [UIColor redColor]  [UIColor whiteColor]來生成。類似的方法共有15個,其中比較特別的是 clearColor 它代表透明的。
 
另一個較常用的生成方式是使用另一個 Class method,【colorWithRed:CGfloat  green:CGfloat  blue:CGfloat  alpha:CGfloat】,共需紅/綠/藍/透明度  等四個參數,RGB 是用一個 0~1 的浮點數來設定的 0 代表沒有,1 代表全部,透明度alpha,則是 0 代表完全透明,1 代表不透明。比方說,如果要一個純紅色的顏色,就可以用 [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0]。再來我們談一下 UILabel 我們要做的事。我們會設定它的 textColor 顏色,同樣是要求 UIColor ,不再重覆說明。另外我們要設 UILabel 的 textAlignment。它要求一個 UITextAlignment,我們可以從 Help 文件中,查到它是一個結構體如下:

typedef enum {

    UITextAlignmentLeft,
    UITextAlignmentCenter,
    UITextAlignmentRight,

} UITextAlignment;


看起來它是一個簡單的結構體,我們只要設為 UITextAlignmentCenter 就可以置中了。

最後我們要加一個 UIButton,就像是 UILabel,它也要設定 Frame,除此之外我們用 buttonWithType:UIButtonType 的類別方法生成,同時設定它的型式。類似 UIColor 的生成 buttonWithType 需要一個 UIButtonType,而 UIButton 也是一個結構體如下:

typedef enum {

    UIButtonTypeCustom = 0,
    UIButtonTypeRoundedRect,
    UIButtonTypeDetailDisclosure,
    UIButtonTypeInfoLight,
    UIButtonTypeInfoDark,
    UIButtonTypeContactAdd,

} UIButtonType;


我們會用最常見的 UIButtonTypeRoundedRect,也就是圓角的按鈕,

生成的碼為 [UIButton buttonWithType:UIButtonTypeRoundedRect ]

UIButton 還要設一個東西,就是它上面的字。由於 UIButton 不只有字的型式,也有可能是圖片所以有好幾種設定顯示方式的設定方法,我們先不研究細節,先用最簡單的 setTitle:NSString forState:UIControlState 方法來設定上面要顯示的字與狀態。

 

綜合以上,我們要在 load View 方法中要加的程式碼為:

   
    self.view.backgroundColor=[UIColor colorWithRed:0.8 green:0.8 blue:1.0 alpha:1.0];//設為淡藍紫色

    UILabel *myLabel=[[UILabel alloc] init]; 
//建立一個空白的 UILabel 
    [myLabel setFrame:CGRectMake(0.0, 0.0, 320, 44)]; //設定 Label 在左上角起 width 320,height 44
    myLabel.text=@"   Hello World!"; // 設定文字為 Hello World!
    myLabel.textColor=[UIColor blueColor];// 設定文字為藍色
    [myLabel setTextAlignment:UITextAlignmentCenter];//設定文字居中
    [self.view addSubview:myLabel]; // 加到 self.view 中

    UIButton *myButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];//生成一個圓角距形 Button
    [myButton setFrame:CGRectMake(100, 88, 120, 44)];//設定位置大小,大約是中偏上,width 120 
    [myButton setTitle:@"Click" forState:UIControlStateNormal]; //設定為顯示 Click,一般狀態顯示
    [self.view addSubview:myButton]; // 加到 self.view 中


就會出現結果畫面:
        
 
arrow
arrow

    shenfive 發表在 痞客邦 留言(0) 人氣()