UIButton是一個標準的UIControl控件,UIKit提供了一組控件:UISwitch開關、UIButton按鈕、UISegmentedControl分段控件、UISlider滑塊、UITextField文本字段控件、UIPageControl分頁控件。這些控件的基類均是UIControl,而UIControl派生自UIView類,因此每一個控件都有不少視圖的特性,包括附着於其餘視圖的能力。全部控件都擁有一套共同的屬性和方法。html
具體視圖關係以下框架
UIButton *btn1 = [[UIButton alloc]initWithFrame:CGRectMake(10, 10, 80, 44)];
一般採用自定義方法,這樣的方式比較靈活ide
[UIButton buttonWithType:UIButtonTypeCustom];
和UIButtonTypeCustom等同的還有如下方式:post
typedef enum { UIButtonTypeCustom = 0, // 自定義,經常使用方式 UIButtonTypeRoundedRect, //白色圓角矩形,相似偏好設置表格單元或者地址簿卡片 UIButtonTypeDetailDisclosure, //藍色的披露按鈕,可放在任何文字旁 UIButtonTypeInfoLight, //小圓圈信息按鈕,能夠放在任何文字旁 UIButtonTypeInfoDark, //白色背景下使用的深色圓圈信息按鈕 UIButtonTypeContactAdd, //藍色加號(+)按鈕,能夠放在任何文字旁 } UIButtonType;
btn.frame = CGRectMake(10.0, 10.0, 60.0, 44.0); //x, y , weight, height;
或者:學習
[btn setFrame:CGRectMake(20,20,50,50)];
[btn1 setTitle:@"點擊" forState:UIControlStateNormal]; //設置標題 [btn1 setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal]; //設置標題顏色[btn1 setTitleShadowColor:[UIColor grayColor] forState:UIControlStateNormal ];//標題陰影顏色
[btn1 setImage:[UIImageimageNamed:@"btn1Img"] forState:UIControlStateNormal]; //按鈕圖片 [btn1 setBackgroundImage:[UIImageimageNamed:@"btn1BgImg"] forState:UIControlStateNormal]; //背景圖片
UIEdgeInsets insets; // 設置按鈕內部圖片間距 insets.top = insets.bottom = insets.right = insets.left = 10; btn.contentEdgeInsets = insets; //內容間距 bt.titleEdgeInsets = insets; // 標題間距
forState後,能夠選擇如下狀態,經常使用的包括:常態,高亮,禁用,選中;url
enum { UIControlStateNormal = 0, //常態 UIControlStateHighlighted = 1 << 0, // 高亮 UIControlStateDisabled = 1 << 1, //禁用 UIControlStateSelected = 1 << 2, //選中 UIControlStateApplication = 0x00FF0000, //當應用程序標誌使用時 UIControlStateReserved = 0xFF000000 //爲內部框架預留的 }; typedef NSUInteger UIControlState;
高亮時,圖像顏色會加深,若是要關閉此屬性,請設置adjustsImageWhenHighlighted 爲NOspa
btn1.adjustsImageWhenHighlighted = NO;
禁用時,圖像顏色會變淺,若是要關閉此屬性,請設置adjustsImageWhenDisabled 爲NOcode
btn1.adjustsImageWhenDisabled = NO;
選中時,能夠設置按鈕發光,請設置showsTouchWhenHighlighted 爲YESorm
btn1.showsTouchWhenHighlighted = YES;
[btn1 addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside]; //爲按鈕的行爲添加屬性 -(void)btnPressed:(id)sender{ //處理按鈕按下事件 UIButton* btn = (UIButton*)sender; if(btn == btn 1){ NSLog(@"btn1 pressed"); } }
具體見下面的例子。htm