1. 程式人生 > >iOS基礎控制元件--UISwitch

iOS基礎控制元件--UISwitch

UISwitch是一個開關控制元件,一般用在設定介面上的一些開關。由於這個控制元件的一些特性,在開發中並不能很好的滿足設計需求,所以一般不常使用。

UISwitch建立

UISwitch是繼承自UIControl的,是UIView的非直接子類,所以建立也是使用同樣的方法。

    //建立UISwitch,UISwitch的大小是固定的,所以在建立時可以不設定大小。
    //注意,在建立UISwitch時不要以switch命名建立的物件,因為switch是OC的關鍵字。
    UISwitch *mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(100, 300, 0, 0)];

UISwitch的屬性

在UISwitch的標頭檔案中可以看到這個控制元件的屬性

@property(nullable, nonatomic, strong) UIColor *onTintColor NS_AVAILABLE_IOS(5_0) UI_APPEARANCE_SELECTOR;
@property(null_resettable, nonatomic, strong) UIColor *tintColor NS_AVAILABLE_IOS(6_0);
@property(nullable, nonatomic, strong) UIColor *thumbTintColor NS_AVAILABLE_IOS(6
_0) UI_APPEARANCE_SELECTOR; @property(nullable, nonatomic, strong) UIImage *onImage NS_AVAILABLE_IOS(6_0) UI_APPEARANCE_SELECTOR; @property(nullable, nonatomic, strong) UIImage *offImage NS_AVAILABLE_IOS(6_0) UI_APPEARANCE_SELECTOR; @property(nonatomic,getter=isOn) BOOL on;

在實際的開發中我們會發現UISwitch的onImage屬性和offImage屬性是無效的,這裡就不多做解釋了。不信的可以自己去設定一下。

    //定製開關顏色UI
    //tintColor 關狀態下的背景顏色
    mySwitch.tintColor = [UIColor redColor];
    //onTintColor 開狀態下的背景顏色
    mySwitch.onTintColor = [UIColor yellowColor];
    //thumbTintColor 滑塊的背景顏色
    mySwitch.thumbTintColor = [UIColor blueColor];

    //    mySwitch.onImage = [UIImage imageNamed:@"on.png"];   //無效
    //    mySwitch.offImage = [UIImage imageNamed:@"off.png"]; //無效
    //設定開關的背景顏色  設定後會發現開關是矩形的
    mySwitch.backgroundColor = [UIColor yellowColor];

    //判斷開關的狀態
    if (mySwitch.on) {
        NSLog(@"switch is on");
    } else {
        NSLog(@"switch is off");
    }

UISwitch的方法

- (void)setOn:(BOOL)on animated:(BOOL)animated; // does not send action

除了建立方法,只有一個設定開關的方法。

    // 設定開關狀態(預設是 關) 這個方法等同於屬性on的設定
    //    mySwitch.on = YES;
    [mySwitch setOn:YES animated:true];  //animated

UISwitch事件監聽

因為開關有控制互動,所以要有監聽事件,和按鈕一樣,使用方法給開關新增一個監聽。

    //新增事件監聽
    [mySwitch addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];

上面程式碼的解釋和按鈕的監聽事件一樣,只是按鈕一般ControlEvents是點選(UIControlEventTouchUpInside),開關是改變(UIControlEventValueChanged)。

總結

前面說到UISwitch的大小是不能設定的,只能通過縮放變形來改變展示的開關的大小。還有2個屬性的無效,這就使得在開發中這個控制元件有很大的侷限性,越是開放的東西應用才能越廣泛。在一些設計中也會有一些開關,但是因為設計的多樣性不能使用UISwitch。所以UIView的靈活運用就很重要,使用UIView也可以製作一個精美的開關。