2010年10月26日 星期二

iPhone 開發筆記08: Setting a Background Color for UIButton

參考來源:
Cocoa Is My Girlfriend » Fun With UIButtons and Core Animation Layers
http://www.cimgf.com/2010/01/28/fun-with-uibuttons-and-core-animation-layers/

步驟:
A. 在 Interface Builder 裡, 設定所使用的 UIButton 的 Attributes TypeCustom.
B. 在 Xcode 的 Resource 裡, 新增 QuartzCore framework, 並在 xxxViewController.h 檔中引入:
import <QuartzCore/QuartzCore.h>

UIButton *button1;
. . . .
@property (nonatomic, retain) IBOutlet UIButton *button1;


C. 在 xxxViewController.m 檔中的 - (void)viewDidLoad: 內加入以下的程式碼:
@synthesize button1;
. . . .
- (void)viewDidLoad {

    [[button1 layer] setCornerRadius:8.0f];
    [[button1 layer] setMasksToBounds:YES];
    [[button1 layer] setBorderWidth:1.0f];
   
    /* set "green border" on the layer passing it a CGColorRef. */
    [[button1 layer] setBorderColor:[[UIColor greenColor] CGColor]];
   
    /* set the background color */
    // Core Animation way
    //[[button1 layer] setBackgroundColor:[[UIColor redColor] CGColor]];

    // UIView way
    [button1 setBackgroundColor:[UIColor redColor]];

    [super viewDidLoad];

}

說明:
1. With this code the layer gets a corner radius of 8.0

2. and the -setMasksToBounds: tells the button's layer to mask any layer content that comes below it in the layer tree. This is necessary in order for the layer to mask off the rounded corners.

3. Finally, set the border width to 1.0 to display an outline around the button.

4. The default color for this border is black. You can change it to anything you like using -setBorderColor: on the layer passing it a CGColorRef (e.g. [[UIColor greenColor] CGColor] would give you a green border).

5. You can set the background color in Interface Builder or in code–whichever you prefer. There are two ways to do this in code. One using the layer and one using the UIView call to -setBackgroundColor.

The main difference between the two is that the layer works with a CGColorRef while the UIView works with a UIColor. It' s a subtle difference, but one that you should know.

沒有留言:

張貼留言

注意:只有此網誌的成員可以留言。