iPhone開發(fā)進階(4)編程定制UIButton案例實現(xiàn)
iPhone開發(fā)編程定制UIButton案例實現(xiàn)是本文要介紹的內(nèi)容,主要是來講述一下自動創(chuàng)建 UIButton 而不使用 XIB 文件。通過這一節(jié)的學(xué)習(xí),我們可以掌握不通過 XIB (InterfaceBuilder) 來使用 UIControl 的 addTarget 方法、對應(yīng)相應(yīng)的事件動作。
具體的例子是基于上篇CustomViewController 類,并且按鈕按下是計數(shù)器加一,并顯示在視圖上。
首先,在 CustomViewController 類中添加技術(shù)用的變量 count。
- @interface CustomViewController : UIViewController {
- int count; // 計數(shù)器變量。
- }
- @end
接下來,添加按鈕按下時調(diào)用的方法。
- -(void)countup:(id)inSender {
- count++; // 計數(shù)器自加
- // inSender 是被點擊的 Button 的實例,下面設(shè)置其標題
- [inSender setTitle:[NSString
- stringWithFormat:@"count:%d", count]
- forState:UIControlStateNormal];
- }
setTitle 方法設(shè)定 UIButton 的標題。使用 forState: 來指定該標題顯示的狀態(tài)(按下,彈起,通常),這里指定通常狀態(tài)顯示的標題。當然,使用 UIControlStateNormal 也是可以的。
注冊按鈕按下時的事件函數(shù)可以通過 UIControl 類中的 addTarget:action:forControlEvents: 方法(UIButton 繼承了UIControl 類,所以可以直接使用)。如下所示:
- - (void)viewDidLoad {
- [super viewDidLoad];
- self.view.backgroundColor = [UIColor blueColor];
- UIButton* button = [UIButton buttonWithType:UIButtonTypeInfoLight];
- button.frame = CGRectMake(100,100,100,100);
- // 注冊按鈕按下時的處理函數(shù)
- [button addTarget:self action:@selector(countup:)
- forControlEvents:UIControlEventTouchUpInside];
- [self.view addSubview:button];
forControlEvents: 中設(shè)定 UIControlEventTouchUpInside 是指在按鈕上按下時響應(yīng)。
因為動作函數(shù)(countup)的類型是
- -(void)countup:(id)inSender
則在注冊的時候需要寫 countup: 。
而如果函數(shù)類型是
- -(void)countup
的話,則是 countup ,這時 addTarget 接收的函數(shù)類型如下所示:
- - (void) countup:(id)sender forEvent:(UIEvent *)event
同一響應(yīng),也可以注冊多個處理,比如下面的代碼,將上面兩種類型的動作函數(shù)都注冊了:
- // ***種處理方法
- -(void)countup:(id)inSender {
- count++;
- [inSender setTitle:[NSString
- stringWithFormat:@"count:%d", count]
- forState:UIControlStateNormal];
- }
- // 第二種處理方法
- -(void)countup {
- count++;
- }
- -(void)countup:(id)inSender forEvent:(UIEvent *)event {
- count++;
- [inSender setTitle:[NSString
- stringWithFormat:@"count:%d", count]
- forState:UIControlStateNormal];
- }
- - (void)viewDidLoad {
- [super viewDidLoad];
- self.view.backgroundColor = [UIColor blueColor];
- UIButton* button = [UIButton buttonWithType:UIButtonTypeInfoLight];
- button.frame = CGRectMake(100,100,100,100);
- // 注冊***種方法
- [button addTarget:self action:@selector(countup:)
- forControlEvents:UIControlEventTouchUpInside];
- // 注冊第二種方法
- [button addTarget:self action:@selector(countup)
- forControlEvents:UIControlEventTouchUpInside];
- [button addTarget:self action:@selector(countup:forEvent:)
- forControlEvents:UIControlEventTouchUpInside];
- [self.view addSubview:button];
- }
編譯以后,顯示如下:
小結(jié):iPhone開發(fā)編程定制UIButton案例實現(xiàn)的內(nèi)容介紹完了,希望通過本文的學(xué)習(xí)能對你有所幫助!如果想繼續(xù)深入了解的話,請參考以下幾篇文章:
iPhone開發(fā)進階(1)iPhone應(yīng)用程序項目構(gòu)成案例實現(xiàn)