码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2017-08-01 15:40:27      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:super   type   设置   int   code   ace   als   color   frame   

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)

标签:super   type   设置   int   code   ace   als   color   frame   

原文地址:http://www.cnblogs.com/Free-Thinker/p/7268547.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!