UIButton的類是一個(gè)UIControl子類,它實(shí)現(xiàn)了在觸摸屏上的按鈕活逆。觸摸一個(gè)按鈕攔截事件和動(dòng)作消息發(fā)送到目標(biāo)對(duì)象時(shí)些阅,它的挖掘。設(shè)定的目標(biāo)和行動(dòng)方法都繼承自UIControl揭措。這個(gè)類提供了方法來(lái)設(shè)置標(biāo)題胯舷,圖像,按鈕等外觀屬性绊含。通過(guò)使用set方法桑嘶,你可以指定一個(gè)不同的外觀為每個(gè)按鈕狀態(tài)。
創(chuàng)建一個(gè)UIButton很簡(jiǎn)單,只需要記清楚他的屬性就可.
第一步創(chuàng)建一個(gè)Button對(duì)象
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
UIbutton的創(chuàng)建使用的是類方法 所以不用使用alloc,故在MRC的情況下button的創(chuàng)建不需要手動(dòng)release.
第二步吧Button放在View上
button.frame = CGRectMake(100, 100, 100, 100);
第三步給button ?addTarget設(shè)置點(diǎn)擊方法
[button addTarget:self action:@selector(clicked:) forControlEvents:UIControlEventTouchUpInside];
在創(chuàng)建方法外設(shè)置點(diǎn)擊方法
-(void)clicked:(UIButton *)button{
if (button.selected == NO) {
button.selected = YES;
}else{
button.selected = NO;
}
NSLog(@"點(diǎn)到我了");
}
這樣基本的一個(gè)Button 就設(shè)置完了
UIButton的各種屬性
在創(chuàng)建時(shí)可選的Button的樣式能夠定義的button類型有以下6種.
// ? typedef enum {
//? ? ? ? UIButtonTypeCustom = 0,? ? ? ? ? 自定義風(fēng)格
//? ? ? ? UIButtonTypeRoundedRect,? ? ? ? 圓角矩形
//? ? ? ? UIButtonTypeDetailDisclosure,? ? 藍(lán)色小箭頭按鈕躬充,主要做詳細(xì)說(shuō)明用
//? ? ? ? UIButtonTypeInfoLight,? ? ? ? ? 亮色感嘆號(hào)
//? ? ? ? UIButtonTypeInfoDark,? ? ? ? ? ? 暗色感嘆號(hào)
//? ? ? ? UIButtonTypeContactAdd,? ? ? ? ? 十字加號(hào)按鈕
//? ? } UIButtonType;
button的底色設(shè)置
button.backgroundColor = [UIColor clearColor];
設(shè)置button標(biāo)題
[button1 setTitle:@"點(diǎn)擊" forState:UIControlStateNormal];
設(shè)置button填充圖片
[button1 setImage:[UIImage imageNamed:@"btng.png"] forState:UIControlStateNormal];
?forState: 這個(gè)參數(shù)的作用是定義按鈕的文字或圖片在何種狀態(tài)下才會(huì)顯現(xiàn)
//以下是幾種狀態(tài)
//? ? enum {
//? ? ? ? UIControlStateNormal? ? ? = 0,? ? ? ? 常規(guī)狀態(tài)顯現(xiàn)
//? ? ? ? UIControlStateHighlighted? = 1 << 0,? ? 高亮狀態(tài)顯現(xiàn)
//? ? ? ? UIControlStateDisabled? ? = 1 << 1,? ? 禁用的狀態(tài)才會(huì)顯現(xiàn)
//? ? ? ? UIControlStateSelected? ? = 1 << 2,? ? 選中狀態(tài)
//? ? ? ? UIControlStateApplication? = 0x00FF0000, 當(dāng)應(yīng)用程序標(biāo)志時(shí)
//? ? ? ? UIControlStateReserved? ? = 0xFF000000? 為內(nèi)部框架預(yù)留逃顶,可以不管他
//? ? };
?默認(rèn)情況下,當(dāng)按鈕高亮的情況下麻裳,圖像的顏色會(huì)被畫深一點(diǎn)口蝠,如果這下面的這個(gè)屬性設(shè)置為no器钟, 那么可以去掉這個(gè)功能
button1.adjustsImageWhenHighlighted = NO;
跟上面的情況一樣津坑,默認(rèn)情況下,當(dāng)按鈕禁用的時(shí)候傲霸,圖像會(huì)被畫得深一點(diǎn)疆瑰,設(shè)置NO可以取消設(shè)置
button1.adjustsImageWhenDisabled = NO;
下面的這個(gè)屬性設(shè)置為yes的狀態(tài)下,按鈕按下會(huì)發(fā)光
button1.showsTouchWhenHighlighted = YES;
當(dāng)然button因?yàn)槔^承與UIView所以View的大部分屬性他都可以使用比如圓角
button.layer.masksToBounds = YES;
button.layer.cornerRadius = 50.0;
button.layer.borderWidth = 1.0;
button.layer.borderColor = [[UIColor whiteColor] CGColor];
最后只需要把button加入到當(dāng)前視圖就可以打開(kāi)模擬器使用了
[self.view addSubview:button];
以上是一個(gè)建的UIButton的使用方式 ? 應(yīng)為UIButton比較常用 ?所以他的屬性能很快被大家記住.
希望大家在接下來(lái)的iOS學(xué)習(xí)中努力.