UISwitch如果放置在一个UIView里,那么它就会根据父控件UIView固定好大小,不管你怎么设置UISwitch的frame都改变不了它的大小,解决的办法如下:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor grayColor];
UIView *mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 50, kScreenWidth, 30)];
mainView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:mainView];
UISwitch *nameSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(kScreenWidth / 2.0, 0, 25, 15)];
nameSwitch.on = YES;
nameSwitch.transform = CGAffineTransformMakeScale(0.7, 0.6); //改变大小的关键代码
[mainView addSubview:nameSwitch];
}
补充:
1.UISwitch的初始化
UISwitch *switchView = [[UISwitch alloc] initWithFrame:CGRectMake(54.0f, 16.0f, 100.0f, 28.0f)];
2.设置UISwitch的初始化状态
switchView.on = YES;//设置初始为ON的一边
3.UISwitch事件的响应
[switchView addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];