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