iOS開發系列之一 - UIButton 用法小結

// 初始化按鈕並設置類型
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];

// 能夠定義的UIButton類型有以下6種:
//    typedef enum {
//        UIButtonTypeCustom = 0,          自定義風格
//        UIButtonTypeRoundedRect,         圓角矩形
//        UIButtonTypeDetailDisclosure,    藍色小箭頭按鈕,主要做詳細說明用
//        UIButtonTypeInfoLight,           亮色感嘆號
//        UIButtonTypeInfoDark,            暗色感嘆號
//        UIButtonTypeContactAdd,          十字加號按鈕
//    } UIButtonType;

// 設置按鈕大小和位置
btn.frame = CGRectMake(20, 360, 280, 45);
// 設置按鈕背景顏色
btn.backgroundColor = [UIColor colorWithRed:254/255.0f green:254/255.0f blue:254/255.0f alpha:1.0f];
// 設置按鈕文字
[btn setTitle:@"Normal" forState:UIControlStateNormal];
[btn setTitle:@"Pressed" forState:UIControlStateHighlighted];

// forState這個參數的作用是定義按鈕的文字或圖片在何種狀態下才會顯現,以下是幾種狀態:
//    enum {
//        UIControlStateNormal       = 0,           常規狀態顯現
//        UIControlStateHighlighted  = 1 << 0,      高亮狀態顯現
//        UIControlStateDisabled     = 1 << 1,      禁用的狀態纔會顯現
//        UIControlStateSelected     = 1 << 2,      選中狀態
//        UIControlStateApplication  = 0x00FF0000,  當應用程序標誌時
//        UIControlStateReserved     = 0xFF000000   爲內部框架預留,可以不管他
//    };

// 設置按鈕文字顏色
[btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
// 設置按鈕文字字體
[btn.titleLabel setFont:[UIFont systemFontOfSize:17]];
[btn.layer setMasksToBounds:YES];
// 設置按鈕四個圓角半徑
[btn.layer setCornerRadius:4.0];
// 設置按鈕邊框寬度
[btn.layer setBorderWidth:0.5];
// 設置按鈕邊框顏色
CGColorRef colorref = CGColorCreate(CGColorSpaceCreateDeviceRGB(),(CGFloat[]){168/255.0f, 168/255.0f, 168/255.0f, 1.0});
[btn.layer setBorderColor:colorref];
// 去除按鈕在疊加視圖中的按下延遲
tableView.delaysContentTouches = NO;
// 添加點擊事件
[btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];

// 在視圖中顯示按鈕
[tableView addSubview:btn];

// 按鈕點擊事件
- (void)btnAction:(id)sender
{
    // do something
}

本文固定鏈接:http://www.itechzero.com/ios-development-series-one-uibutton-usage-summary.html,轉載請註明出處。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章