您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

UIButton 完整指南:三種狀態、屬性設定與 IBAction 的注意事項

編輯:iOS 相關教學

UIButton 幾乎是所有互動的起點。它既能顯示文字、也能顯示圖片,還能調整內部圖文的位置。本文整理按鈕的三種狀態、常用屬性、事件綁定,以及初學者最常卡住的幾個語法細節。

一、按鈕的三種狀態

同一顆按鈕在不同階段有不同外觀,這就是「狀態」的概念。設定屬性時透過 forState: 指定要套用在哪個狀態上。

  • normal(普通狀態):預設情況,對應 UIControlStateNormal
  • highlighted(高亮狀態):手指按下尚未放開時,對應 UIControlStateHighlighted
  • disabled(失效狀態):當 enabled 屬性為 NO 時進入此狀態,按鈕無法被點擊,對應 UIControlStateDisabled

二、兩個實務上的注意點

  1. 從 Xcode 5 起,圖片資源統一放在 Images.xcassets 中管理,可以直接把圖片拖進去。
  2. 若多個控制項共用同一段程式碼,通常用 tag 來區分是哪一個被觸發。

三、修改 frame 的正確語法

Objective-C 不允許直接修改「物件的結構體屬性的成員」,但允許修改「物件的結構體屬性」本身。所以改 frame 的 y 值要分三步:

#import "LFViewController.h"

@interface LFViewController ()
@property (weak, nonatomic) IBOutlet UIButton *headImageView;
@end

@implementation LFViewController

- (IBAction)move
{
    // 1. 取出結構體屬性
    CGRect rect = self.headImageView.frame;
    // 2. 修改暫存變數的成員
    rect.origin.y -= 20;
    // 3. 整個設回去
    self.headImageView.frame = rect;
}

@end

寫成 self.headImageView.frame.origin.y -= 20; 是編譯不通的。

四、用 tag 與枚舉取代魔法數字

程式碼中直接寫 0、1、2、3 判斷方向,就是所謂的「魔法數字(Magic Number)」——後續維護的人看不懂 0 代表什麼。用枚舉可以避免這個問題:

#import "LFViewController.h"

/**
 * 使用 git 的簡單流程:
 * 1. 建立專案時勾選 git
 * 2. 開發告一段落後,選 Source Control → Commit,並撰寫有意義的註解
 */

// 列舉的本質就是整數,指定第一個值之後,後續會自動遞增
typedef enum {
    kMovingDirTop = 10,
    kMovingDirBottom,
    kMovingDirLeft,
    kMovingDirRight,
} kMovingDir;

#define kMovingDelta 50

@interface LFViewController ()
@property (weak, nonatomic) IBOutlet UIButton *headImageView;
@end

@implementation LFViewController

- (IBAction)move:(UIButton *)button
{
    CGPoint p = self.headImageView.center;

    switch (button.tag) {
        case kMovingDirTop:    p.y -= kMovingDelta; break;
        case kMovingDirBottom: p.y += kMovingDelta; break;
        case kMovingDirLeft:   p.x -= kMovingDelta; break;
        case kMovingDirRight:  p.x += kMovingDelta; break;
    }

    // 首尾式動畫
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:1.0];
    self.headImageView.center = p;
    [UIView commitAnimations];
}

- (IBAction)zoom:(UIButton *)button
{
    CGRect rect = self.headImageView.bounds;

    // C 語言中,關於 bool 的判斷是「非零即真」
    if (button.tag) {
        rect.size.width  += 50;
        rect.size.height += 50;
    } else {
        rect.size.width  -= 50;
        rect.size.height -= 50;
    }

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:2.0];
    self.headImageView.bounds = rect;
    [UIView commitAnimations];
}

@end

五、補充筆記

1. IBAction 的參數

寫成 - (IBAction)left:(UIButton *)button 的三個要點:

  • Objective-C 中,絕大多數控制項的監聽方法,第一個參數就是觸發它的控制項本身。
  • 從 storyboard 拉線時,預設參數型別是 id。
  • 若希望在方法內直接使用 UIButton 特有的屬性,可以在拉線時或拉完之後把參數型別改成 UIButton *。

2. 修改結構體成員的三步驟

  1. 用暫存變數記下該結構體屬性
  2. 修改暫存變數的成員
  3. 把暫存變數整體設回物件

3. frame、bounds、center 的差別

  • frame:可改位置與尺寸(以父視圖座標系為基準)
  • bounds:只改尺寸
  • center:只改位置

4. 首尾式動畫的結構

// beginAnimations 表示之後的程式碼要「參與動畫」
[UIView beginAnimations:nil context:nil];
// 指定動畫持續時間
[UIView setAnimationDuration:2.0];

self.headImageView.bounds = rect;
// ……其他要一起動的屬性

// commitAnimations 把 begin 之後的所有動畫一次提交
[UIView commitAnimations];

首尾配對缺一不可,否則動畫不會發生。

六、UIButton 常用屬性速查

建立按鈕

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

可選的六種樣式:

typedef enum {
    UIButtonTypeCustom = 0,          // 自訂風格
    UIButtonTypeRoundedRect,         // 圓角矩形
    UIButtonTypeDetailDisclosure,    // 藍色小箭頭,常用於「詳細說明」
    UIButtonTypeInfoLight,           // 亮色感嘆號
    UIButtonTypeInfoDark,            // 暗色感嘆號
    UIButtonTypeContactAdd,          // 十字加號
} UIButtonType;

位置與尺寸

button1.frame = CGRectMake(20, 20, 280, 40);
[button setFrame:CGRectMake(20, 20, 50, 50)];

背景顏色

button1.backgroundColor = [UIColor clearColor];
[button setBackgroundColor:[UIColor blueColor]];

狀態(forState:)

forState: 決定所設定的文字或圖片在哪個狀態下才會顯示:

enum {
    UIControlStateNormal       = 0,           // 常規狀態
    UIControlStateHighlighted  = 1 << 0,     // 高亮
    UIControlStateDisabled     = 1 << 1,     // 禁用
    UIControlStateSelected     = 1 << 2,     // 選中
    UIControlStateApplication  = 0x00FF0000, // 供應用程式使用
    UIControlStateReserved     = 0xFF000000  // 框架預留
};

@property (nonatomic, getter=isEnabled) BOOL enabled;     // 預設 YES;為 NO 時忽略觸碰事件
@property (nonatomic, getter=isSelected) BOOL selected;   // 預設 NO
@property (nonatomic, getter=isHighlighted) BOOL highlighted;

圖片與背景圖

[button setImage:[UIImage imageNamed:@"checkmarkControllerIcon"]
        forState:UIControlStateNormal];

[button setBackgroundImage:[UIImage imageNamed:@"checkmarkControllerIcon"]
                  forState:UIControlStateNormal];

兩者的差別:setImage: 的圖片會參與內部排版(受 titleEdgeInsets 等影響),setBackgroundImage: 則是鋪滿整個按鈕背景。

標題文字與顏色

[button1 setTitle:@"點擊" forState:UIControlStateNormal];
[button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];

按下時發光

button.showsTouchWhenHighlighted = YES;

加入與移除事件

[button1 addTarget:self
            action:@selector(butClick:)
  forControlEvents:UIControlEventTouchUpInside];

[btn removeTarget:nil action:nil forControlEvents:UIControlEventTouchUpInside];

圖片與文字的間距

UIEdgeInsets insets;
insets.top = insets.bottom = insets.left = insets.right = 10;

bt.contentEdgeInsets = insets; // 按鈕內容(含圖片與文字)的外緣間距
bt.titleEdgeInsets   = insets; // 標題文字的外緣間距
bt.imageEdgeInsets   = insets; // 圖片的外緣間距

調整這三個 insets 的組合,就能做出「圖片置中、文字在下方」這類常見版型。

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