标签:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (strong,nonatomic) UISwitch *phoneSwitch;
@property (strong,nonatomic) UIView *lampView;
@property (strong,nonatomic) UIView *lampView1;
@property (strong,nonatomic) UIView *lampView2;
@property (strong,nonatomic) UISlider *lampSlider;
@end
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//开关:Switch控件的初始化,确定它的在父视图的位置和它的大小
self.phoneSwitch=[[UISwitch alloc]initWithFrame:CGRectMake(150, 100, 100, 44)];
//添加委托方法:当控件self.phoneSwitch被 UIControlEventValueChanged 此种触动而发生变化时,调用lampChange方法
[self.phoneSwitch addTarget:self action:@selector(lampChange) forControlEvents:UIControlEventValueChanged];
//将self.phoneSwitch视图控件加载到父视图
[self.view addSubview:self.phoneSwitch];
//手电筒:视图控件self.lampView的初始化,确定其大小和在父视图中的位置
self.lampView=[[UIView alloc]initWithFrame:CGRectMake(150, 200, 100, 100)];
//将此视图从矩形变为圆形
self.lampView.layer.cornerRadius=50;
//给视图加背景色
self.lampView.backgroundColor=[UIColor whiteColor];
//将视图添加到父视图上
[self.view addSubview:self.lampView];
//手电筒亮度调节按钮:Slider控件视图的初始化,确定其大小和在父视图上的位置
self.lampSlider=[[UISlider alloc]initWithFrame:CGRectMake(100, 400, 200, 50)];
//灯的初始亮度:Slider控件的初始值(self.lampSlider.Value)
[self.lampSlider setValue:0.5];
//添加委托方法:当控件self.lampSlider发生变化时,调用方法lampChange
[self.lampSlider addTarget:self action:
@selector(lampChange) forControlEvents:UIControlEventValueChanged];
//将视图添加到父视图
[self.view addSubview:self.lampSlider];
}
-(void)lampChange
{
//开关打开后
if (self.phoneSwitch.isOn) {
//灯打开后变为红色
self.lampView.backgroundColor=[UIColor redColor];
//slider控件的调节来调节灯的亮度
self.lampView.alpha=self.lampSlider.value;
}
//关灯后
else {
//关灯后灯变为原本颜色
self.lampView.backgroundColor=[UIColor whiteColor];
}
}
标签:
原文地址:http://www.cnblogs.com/Always-LuoHan/p/UISwitch.html