自定義UISwitch顏色


UISwithch屬性說明:

  1. tintColor:開關處於關閉狀態時的顏色
  2. onTintColor:開關處於開啟狀態時的顏色
  3. thumbTintColor:開關的狀態鈕顏色
  4. onImage:開關處於開啟狀態時的圖片(iOS7及之后設置無效)
  5. offImage:開關處於關閉狀態時的圖片(iOS7及之后設置無效)
  6. backgroundColor:整個開關背景色,設置后可以明顯看到一個矩形背景

iOS系統內置了UISwithch控件的size,所以通過代碼調整UISwithch的大小無效.

oc代碼:

- (void)viewDidLoad {
[super viewDidLoad];

self.mSwitch.tintColor = [UIColor redColor];
self.mSwitch.onTintColor = [UIColor blackColor];
self.mSwitch.thumbTintColor = [UIColor yellowColor];
self.mSwitch.backgroundColor = [UIColor purpleColor];

//iOS7&later設置無效
self.mSwitch.onImage = [UIImage imageNamed:@"on"];
self.mSwitch.offImage = [UIImage imageNamed:@"off"];

//設置無效
UISwitch *s = [[UISwitch alloc]initWithFrame:CGRectMake(100, 100, 200, 200)];
[self.view addSubview:s];
}


- (IBAction)switchValueDidChanged:(UISwitch *)sender {
NSLog(@"%@",sender.isOn?@"switch is On":@"switch is Off");
}

swift代碼:

@IBOutlet weak var mSwitch: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
self.mSwitch.tintColor = UIColor.redColor()
self.mSwitch.onTintColor = UIColor .yellowColor()
self.mSwitch.thumbTintColor = UIColor.blueColor()
self.mSwitch.backgroundColor = UIColor.clearColor()

var sw = UISwitch(frame: CGRectMake(0, 0, 0, 0))
sw.addTarget(self, action: "switchValueDidChanged", forControlEvents: UIControlEvents.ValueChanged)
self.view.addSubview(sw)
}
@IBAction func switchValueDidChanged(sender: UISwitch) {
var result = sender.on ? "on" : "off"
println("switch is \(result)")
}

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
  © 2014-2022 ITdaan.com 联系我们: