iOS开发技巧 - 使用和定制开关控件(UISwitch)
2016-08-15 17:18
423 查看
1. 初始化加载到视图界面
(Swift)
(Objective-C)
2. 设置开关状态
(Swift)
(Objective-C)
3. 判断开关状态
(Swift)
(Objective-C)
4. 添加事件监听
(Swift)
(Objective-C)
5. 定制开关UI
(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)
- iOS 9应用开发教程之使用开关滑块控件以及滚动部署视图
- UISwitch 开关控件—IOS开发
- iOS 9应用开发教程之使用开关滑块控件以及滚动部署视图
- UISwitch 开关控件—IOS开发
- 【iOS开发-12】UISwitch开关控件属性介绍以及获取开关状态并做出响应
- ios基础控件之开关按钮(UISwitch) 分类: ios开发 2015-04-08 21:24 188人阅读 评论(0) 收藏
- UISwitch 开关控件—IOS开发
- iOS 5 编程(2)-开关(UISwitch)、分段控件(UISegmentedControl)和Web视图(UIWebView)控件的使用
- iOS开发-UI控件:UISwitch控件两种使用方法和监听
- UISwitch 开关控件—IOS开发
- UISwitch 开关控件—IOS开发
- iOS开发之UISwitch控件的使用
- IOS开发(2)之UISwitch开关控件
- [iOS开发必备技巧之]使用IB定制UITableViewCell
- UISwitch 开关控件—IOS开发
- iOS开发UISwitch开关控件属性介绍以及获取开关状态并做出响应
- iOS 9应用开发教程之使用开关滑块控件以及滚动部署视图
- UISwitch 开关控件—IOS开发
- UISwitch 开关控件—IOS开发