您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 基礎:UIButton 的簡單操作與事件綁定

編輯:iOS 開發綜合

UIButton 的風格類型

typedef NS_ENUM(NSInteger, UIButtonType) {
    UIButtonTypeCustom = 0,          // 自定義,無按鈕類型
    UIButtonTypeSystem,              // 系統標準按鈕
    UIButtonTypeDetailDisclosure,    // 詳細說明箭頭
    UIButtonTypeInfoLight,           // 亮色資訊鈕
    UIButtonTypeInfoDark,            // 暗色資訊鈕
    UIButtonTypeContactAdd,          // 添加聯絡人
    UIButtonTypeRoundedRect = UIButtonTypeSystem, // 已棄用,改用 UIButtonTypeSystem
};

簡單操作

UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
button.tag = 100; // 給 Button 添加標記,方便在不同方法中取得同一控件
button.frame = CGRectMake(30, 170, 200, 40);
[self.window addSubview:button];

// 設置按鈕文字,需指定狀態
[button setTitle:@"按鈕" forState:UIControlStateNormal];
// [button setTitle:@"Hello" forState:UIControlStateHighlighted];
[button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];

// 高亮時觸發
button.showsTouchWhenHighlighted = YES;

// 為 button 綁定事件
[button addTarget:self                       // 接收消息的對象
           action:@selector(buttonAction:)    // 觸發時發送的消息
 forControlEvents:UIControlEventTouchUpInside]; // 觸發方式

Button 的處理方法

- (void)buttonAction {
    NSLog(@"咔");
    // 透過 tag 從父視圖中取得 button
    UIButton *btn = (UIButton *)[self.window viewWithTag:100];
    [btn setTitle:@"點我" forState:UIControlStateNormal];
    // 讓 Button 失效(移除事件)
    [btn removeTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
}

- (void)buttonAction:(UIButton *)sender {
    sender.backgroundColor = [UIColor redColor];
}

透過 tag 標記控件、addTarget:action:forControlEvents: 綁定事件,以及 removeTarget:action:forControlEvents: 移除事件,就構成了 UIButton 最基礎也最常用的操作模式。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved