一、IOS UIButton的基本屬性
// 創(chuàng)建一個(gè)Button對(duì)象歧蕉,根據(jù)類型來(lái)創(chuàng)建button
// 圓角類型button:UIButtonTypeRoundedRect
// 通過(guò)類方法來(lái)創(chuàng)建buttonWithType: 類名 + 方法名灾部,不能通過(guò)alloc init方式創(chuàng)建
UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(100, 100, 100, 40);
// 按鈕的正常狀態(tài)
[button setTitle:@"點(diǎn)擊" forState:UIControlStateNormal];
// 按鈕的按下?tīng)顟B(tài)
[button setTitle:@"按下" forState:UIControlStateHighlighted];
// 設(shè)置按鈕的背景色
button.backgroundColor = [UIColor redColor];
// 設(shè)置正常狀態(tài)下按鈕文字的顏色,如果不寫其他狀態(tài)惯退,默認(rèn)都是用這個(gè)文字的顏色
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
// 設(shè)置按下?tīng)顟B(tài)文字的顏色
[button setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
// 設(shè)置按鈕的風(fēng)格顏色,只有titleColor沒(méi)有設(shè)置的時(shí)候才有用
[button setTintColor:[UIColor whiteColor]];
// titleLabel:UILabel控件
button.titleLabel.font = [UIFont systemFontOfSize:25];
上面就是 UIButton 基本屬性的使用赌髓。
二、自定義帶圖片的 UIButton
UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(100, 200, 100, 100);
UIImage* icon1 = [UIImage imageNamed:@"img1"];
UIImage* icon2 = [UIImage imageNamed:@"img2"];
[button setImage:icon1 forState:UIControlStateNormal];
[button setImage:icon2 forState:UIControlStateHighlighted];
其實(shí)也是很簡(jiǎn)單的催跪,就是創(chuàng)建了兩個(gè)圖像類锁蠕,然后設(shè)置到 button 上面。
三懊蒸、給 UIButton 添加點(diǎn)擊事件
[button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
button.tag = 110;
// 對(duì)應(yīng)觸發(fā)函數(shù)如下
// 參數(shù)為調(diào)用此函數(shù)按鈕對(duì)象本身
-(void) clickButton:(UIButton*) btn {
if (btn.tag == 100) {
NSLog(@"有參被點(diǎn)擊");
}
}
可以看到觸發(fā)函數(shù)的添加也是很簡(jiǎn)單的匿沛,每個(gè)UIButton 都有一個(gè)可以設(shè)置的 tag,通過(guò)這個(gè) tag榛鼎,我們可以區(qū)分當(dāng)多個(gè) UIButton 共用同一個(gè)觸發(fā)函數(shù)的時(shí)候逃呼。
如果本身就沒(méi)有任何參數(shù)傳遞鳖孤,我們可以把 clickButton 后面的 : 去掉,然后更改對(duì)應(yīng)的觸發(fā)函數(shù)參數(shù)個(gè)數(shù)就好了抡笼。