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];