2014
Feb
05

UIView 代表一個矩形的顯示區塊,這個區塊裡面,可以包含各種按鈕,文字等等子物件,UIView 本身也有一些基本的 Method 可以使用,如填滿背景色(backgroundColor),邊框(Border),而子物件可以透過 addSubview 加進 UIView 裡,那我們就能夠創造多個 UIView 來完成各種頁面。

UIView 還能夠包含其他的 UIView ,透過多個小型的 UIView 去組成較大型的 UIView,這樣方便程式的擴充與維護,在維護方面,我們一次只需要修改一個小小的 View ,比起一次修改一個大型的 View 會方便很多,而在擴充方面,每一個小的 View 可以快速的被其他更好的 View 取代,更方便的強化 UI 的呈現。

UIView 顯示區域

UIView 的顯示區域有三個要素,分別是 frame, bounds, center。 「frame」 儲存 View 的座標 (x, y )與寬、高,「center」 是指 View 的中心點,當 View 有放大、縮小,旋轉功能時,就必須靠中心點來定位,「bounds」 則是 View 可畫圖的區塊,bounds 也包含座標與寬高,但座標的原點是以 frame 的 x , y 為準,所以通常 bounds 的 x 與 y 就是 (0, 0),而寬高就是 frame 的寬高。

建立一個 UIView

我畫一個 座標 (0, 0),寬 200 ,高 200 的 View。

Draw UIView
  1. self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
  2. self.window.backgroundColor = [UIColor whiteColor];
  3. [self.window makeKeyAndVisible];
  4.  
  5. CGRect viewRect = CGRectMake(0, 0, 200, 200);
  6. UIView* myView = [[UIView alloc] initWithFrame:viewRect];
  7. [myView setBackgroundColor:[UIColor yellowColor]];
  8. [self.window addSubview:myView];
DEMO
 simple view

View 的旋轉

使用 transform = CGAffineTransformMakeRotation(45); 這能夠將 View 逆時針旋轉 45 度。

Example
  1. self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
  2. self.window.backgroundColor = [UIColor whiteColor];
  3. [self.window makeKeyAndVisible];
  4.  
  5. CGRect viewRect = CGRectMake(50, 150, 200, 200);
  6. UIView* myView = [[UIView alloc] initWithFrame:viewRect];
  7. [myView setBackgroundColor:[UIColor yellowColor]];
  8.  
  9. myView.transform = CGAffineTransformMakeRotation(45);
  10. [self.window addSubview:myView];
DEMO
 view rotate

縮小 View bounds 的寬、高,會使得 View 由中心點開始縮小。

UIView* view = [[UIView alloc ] initWithFrame:self.window.bounds ]

透過上一行 code 可以建立一個滿版的 View,但是我再透過 bounds 的設定將 bounds 縮小,這時 View 就會由中心點開始縮小。

Example
  1. self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
  2. self.window.backgroundColor = [UIColor whiteColor];
  3. [self.window makeKeyAndVisible];
  4. UIView* view = [[UIView alloc] initWithFrame:self.window.bounds];
  5. [view setBackgroundColor:[UIColor yellowColor]];
  6. CGRect b = CGRectMake(0, 0, 200, 200);
  7. view.bounds = b;
  8. [self.window addSubview:view];
DEMO
 view center

用 Xcode UI 建立 UIView

Xcode 提供了強大的 UI 給使用者快速建立各式各樣的 View ,透過 UI 只要滑鼠拖拉住按鈕就能輕鬆的建立各種物件

載入 UIView

透過 loadNibNamed 來載入現有的 UIView。

取得 View 裡面的 物件

如果你使用 Xcode 的 UI 來建立 UIView 裡面的物件,當你希望透過程式來操作 View 裡面的物件時,你必須先對被操作的物件 tag 的屬性,例如我將按鈕的 tag 設定成 100 ,接著就可以用 [view viewWithTag:100] 取得該按鈕 。

Example
  1. UIView* view = [[[NSBundle mainBundle] loadNibNamed:@"mainView" owner:self options:nil] objectAtIndex:0];
  2. UIButton *btn = [view viewWithTag:100];
  3. [btn setTitle:@"test string" forState:UIControlStateNormal];
  4. [self.window addSubview: view];

相關文件


回應 (Leave a comment)