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

iOS UISwitch 開關控件:代碼創建、拖拽綁定與自定義完整解析

編輯:iOS 開發綜合

UISwitch 就是那個左右滑動的「小撥桿」,幾乎所有設置頁都少不了它。它的用法本身不難,難的是三件事:值變化怎麼監聽、拖拽方式怎麼綁定、以及默認樣子太單調時如何自定義。本文按這三條線展開。

一、方式一:純代碼動態創建

新建 Single View Application 項目,在 ViewController.m 的 viewDidLoad 中寫:

- (void)viewDidLoad
{
    [super viewDidLoad];

    UISwitch *switchButton = [[UISwitch alloc] initWithFrame:CGRectMake(50, 100, 20, 10)];
    [switchButton setOn:YES];   // 設置初始為打開狀態
    [switchButton addTarget:self
                     action:@selector(switchAction:)
           forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:switchButton];
}

兩點提醒:一是 UIControlEventValueChanged 是開關控件專屬的事件類型,不要寫成 TouchUpInside;二是別忘了 addSubview:,否則控件創建了卻看不見。

監聽撥動事件

- (void)switchAction:(id)sender
{
    UISwitch *switchButton = (UISwitch *)sender;
    BOOL isButtonOn = [switchButton isOn];
    if (isButtonOn) {
        showSwitchValue.text = @"是";
    } else {
        showSwitchValue.text = @"否";
    }
}

這裡的 showSwitchValue 是一個用於回顯結果的 UILabel。通過 sender 反查控件狀態,是好處很明顯的寫法——多個開關可以共用同一個回應方法。

運行效果:

二、方式二:Interface Builder 拖拽

1. 從控件庫拖一個 UISwitch 到 xib 上。

2. 按 alt + command + return 打開 Assistant Editor,選中開關,按住 Control 拖到 ViewController.h。

3. 在彈窗中選擇 Action 方式(而不是 Outlet),命名並確認。

4. 在 .m 中實現回應方法。邏輯和代碼版完全一致,只是簽名多了 IBAction:

- (IBAction)switchAction:(id)sender {
    UISwitch *switchButton = (UISwitch *)sender;
    BOOL isButtonOn = [switchButton isOn];
    if (isButtonOn) {
        showSwitchValue.text = @"是";
    } else {
        showSwitchValue.text = @"否";
    }
}

若同一個項目裡兩種方式並存,記得把代碼版的方法註釋掉,否則方法名衝突。

三、方式三:自定義外觀

3.1 用 Category 擴展 UISwitch

UISwitch 內部自帶「開 / 關」兩個 UILabel,可以通過遍歷找到它們並改寫文字。封裝成類別後調用更乾淨:

// UISwitch-Extended.h
#import <UIKit/UIKit.h>

@interface UISwitch (tagged)
+ (UISwitch *)switchWithLeftText:(NSString *)tag1 andRight:(NSString *)tag2;
@property (nonatomic, readonly) UILabel *label1;
@property (nonatomic, readonly) UILabel *label2;
@end
// UISwitch-Extended.m
#import "UISwitch-Extended.h"

#define TAG_OFFSET 900

@implementation UISwitch (tagged)

// 遞歸遍歷所有子視圖,給 UILabel 打上可檢索的 tag
- (void)spelunkAndTag:(UIView *)aView withCount:(int *)count
{
    for (UIView *subview in [aView subviews])
    {
        if ([subview isKindOfClass:[UILabel class]])
        {
            *count += 1;
            [subview setTag:(TAG_OFFSET + *count)];
        }
        else
        {
            [self spelunkAndTag:subview withCount:count];
        }
    }
}

- (UILabel *)label1
{
    return (UILabel *)[self viewWithTag:TAG_OFFSET + 1];
}

- (UILabel *)label2
{
    return (UILabel *)[self viewWithTag:TAG_OFFSET + 2];
}

+ (UISwitch *)switchWithLeftText:(NSString *)tag1 andRight:(NSString *)tag2
{
    UISwitch *switchView = [[UISwitch alloc] initWithFrame:CGRectZero];

    int labelCount = 0;
    [switchView spelunkAndTag:switchView withCount:&labelCount];

    if (labelCount == 2)
    {
        [switchView.label1 setText:tag1];
        [switchView.label2 setText:tag2];
    }
    return [switchView autorelease];
}

@end

3.2 直接按層級硬取

還有一種更短但也更「硬」的寫法,按固定索引一路鑽進去:

UISwitch *isFooOrBar = [[UISwitch alloc] init];

((UILabel *)[[[[[[isFooOrBar subviews] lastObject] subviews] objectAtIndex:2] subviews] objectAtIndex:0]).text = @"Foo";
((UILabel *)[[[[[[isFooOrBar subviews] lastObject] subviews] objectAtIndex:2] subviews] objectAtIndex:1]).text = @"Bar";

坦白說,這種代碼可讀性差、且極度依賴私有視圖層級,系統一升級就可能崩潰。了解即可,實際項目不建議使用。

四、常用方法與屬性速查

// 讀取開關狀態
BOOL setting = switchView.isOn;
NSLog(@"%d", setting);

// 設置開關狀態(NO 關閉 / YES 打開),animated 控制是否帶過渡動畫
[switchView setOn:setting animated:YES];

// 打開狀態下的填充色
switchView.onTintColor = [UIColor orangeColor];

// 滑塊(thumb)顏色
switchView.thumbTintColor = [UIColor redColor];

// 控件邊框顏色
switchView.tintColor = [UIColor purpleColor];

// 綁定值變化事件
[switchView addTarget:self
               action:@selector(switchAction:)
     forControlEvents:UIControlEventValueChanged];

五、實踐小結

實際開發中,UISwitch 幾乎不需要自定義內部視圖。iOS 之後提供了 onTintColor、thumbTintColor、tintColor 這組公開屬性,足以覆蓋絕大多數換色需求;若設計稿要求完全不一樣的視覺(比如文字型開關),更合適的做法是新建一個 UIControl 子類自繪,而不是去改動系統私有層級。

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