iOS开发技巧 - 使用和定制开关控件(UISwitch)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS开发技巧 - 使用和定制开关控件(UISwitch)相关的知识,希望对你有一定的参考价值。

1. 初始化加载到视图界面

(Swift)

import UIKit

class ViewController: UIViewController {
    // 1. create a property of type UISwitch
    var mainSwitch:UISwitch!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 2. create switch
        mainSwitch = UISwitch(frame: CGRect(x: 100, y: 100, width: 0, height: 0))
        view.addSubview(mainSwitch)
    }
}

(Objective-C)

#import "ViewController.h"

@interface ViewController ()

// 1. create a property of type UISwitch
@property (nonatomic, strong) UISwitch *mainSwitch;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 2. create switch
    self.mainSwitch = [[UISwitch alloc] initWithFrame:
        CGRectMake(100, 100, 0, 0)];
    [self.view addSubview:self.mainSwitch];
}

@end

 

2. 设置开关状态

(Swift)

mainSwitch.setOn(true, animated: true)

(Objective-C)

[self.mainSwitch setOn:YES];

 

3. 判断开关状态

(Swift)

if mainSwitch.on{
    /* Switch is on */
} else {
    /* Switch is off */
}

(Objective-C)

if ([self.mainSwitch isOn]){
    NSLog(@"The switch is on.");
} else {
    NSLog(@"The switch is off.");
}

 

4. 添加事件监听

(Swift)

mainSwitch.addTarget(self,
    action: "switchIsChanged:",
    forControlEvents: .ValueChanged)
    
func switchIsChanged(sender: UISwitch) {
    println("Sender is = \(sender)")
    if sender.on{
        println("The switch is turned on")
    } else {
        println("The switch is turned off")
    }
}

(Objective-C)

[self.mainSwitch addTarget:self
    action:@selector(switchIsChanged:)
    forControlEvents:UIControlEventValueChanged];
    
- (void) switchIsChanged:(UISwitch *)paramSender {
    NSLog(@"Sender is = %@", paramSender);
    if ([paramSender isOn]){
        NSLog(@"The switch is turned on.");
    } else {
        NSLog(@"The switch is turned off.");
    }
}

 

5. 定制开关UI

/* Adjust the off-mode tint color */
mainSwitch.tintColor = UIColor.redColor()

/* Adjust the on-mode tint color */
mainSwitch.onTintColor = UIColor.brownColor()

/* Also change the knob‘s tint color */
mainSwitch.thumbTintColor = UIColor.greenColor()

以上是关于iOS开发技巧 - 使用和定制开关控件(UISwitch)的主要内容,如果未能解决你的问题,请参考以下文章

Android开发技巧——大图裁剪

iOS系列 基础篇 09 开关滑块和分段控件

iOS开发时间控件怎么强制24小时制(小技巧)

一网打尽__Android 开源代码合集(SwitchButton)

李洪强iOS开发之性能优化技巧

iOS开关按钮UISwitch控件