UISwitch 就是設定頁面上常見的開關,只有開與關兩種狀態。它繼承自 UIView,而蘋果官方所有 UIKit 控件都以 UI 開頭、統一放在 UIKit 框架中。
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController {
// 定義一個開關控件,可在開與關兩種狀態間切換
UISwitch *_mySwitch;
}
@property (retain, nonatomic) UISwitch *mySwitch;
@end
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize mySwitch = _mySwitch;
- (void)viewDidLoad {
[super viewDidLoad];
_mySwitch = [[UISwitch alloc] init];
// 只有 x、y 可以調整;寬高由系統決定,寫了也不會生效
_mySwitch.frame = CGRectMake(100, 200, 180, 40);
// YES 為開啟,NO 為關閉
_mySwitch.on = YES;
// 等價寫法:[_mySwitch setOn:YES];
// 帶動畫的版本:[_mySwitch setOn:YES animated:YES];
[self.view addSubview:_mySwitch];
// 三種顏色分別對應不同部位
[_mySwitch setOnTintColor:[UIColor orangeColor]]; // 開啟狀態的底色
[_mySwitch setThumbTintColor:[UIColor blueColor]]; // 圓形滑塊
[_mySwitch setTintColor:[UIColor greenColor]]; // 整體外框,白色部分其實是父層背景
// 註冊事件:值改變時觸發
[_mySwitch addTarget:self
action:@selector(swChange:)
forControlEvents:UIControlEventValueChanged];
}
// 參數直接帶入開關本身
- (void)swChange:(UISwitch *)sw {
if (sw.on == YES) {
NSLog(@"開關被打開");
} else {
NSLog(@"開關被關閉");
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
幾個容易踩到的小細節:位置可以改、尺寸不能改;setOn:animated: 的第二個參數決定切換時要不要播放動畫;而 setTintColor: 影響的是外框,滑塊兩側的白色其實是父視圖的背景色,並非控件本身可設定的屬性。