「オン」状態の UISwitch ボタンの外観を変更できることを学びましたが、「オフ」状態の UISwitch の色を変更することもできますか?
75651 次
19 に答える
140
これを使ってみてください
yourSwitch.backgroundColor = [UIColor whiteColor];
youSwitch.layer.cornerRadius = 16.0;
@Barry Wyckoff に感謝します。
于 2014-04-03T06:56:10.983 に答える
44
tintColor
プロパティはスイッチで使用できます。
switch.tintColor = [UIColor redColor]; // the "off" color
switch.onTintColor = [UIColor greenColor]; // the "on" color
これには iOS 5 以降が必要です。
于 2013-10-01T18:11:24.310 に答える
1
Xコード11、スウィフト5
Apple がいつ階層を変更するかわからないため、サブビューの使用は好みません。
そのため、代わりにマスク ビューを使用します。
iOS 12、iOS 13で動作します
private lazy var settingSwitch: UISwitch = {
let swt: UISwitch = UISwitch()
// set border color when isOn is false
swt.tintColor = .cloudyBlueTwo
// set border color when isOn is true
swt.onTintColor = .greenishTeal
// set background color when isOn is false
swt.backgroundColor = .cloudyBlueTwo
// create a mask view to clip background over the size you expected.
let maskView = UIView(frame: swt.frame)
maskView.backgroundColor = .red
maskView.layer.cornerRadius = swt.frame.height / 2
maskView.clipsToBounds = true
swt.mask = maskView
// set the scale to your expectation, here is around height: 34, width: 21.
let scale: CGFloat = 2 / 3
swt.transform = CGAffineTransform(scaleX: scale, y: scale)
swt.addTarget(self, action: #selector(switchOnChange(_:)), for: .valueChanged)
return swt
}()
@objc
func switchOnChange(_ sender: UISwitch) {
if sender.isOn {
// set background color when isOn is true
sender.backgroundColor = .greenishTeal
} else {
// set background color when isOn is false
sender.backgroundColor = .cloudyBlueTwo
}
}
于 2020-04-06T13:02:25.547 に答える