I would like to change the default size of the UISwitch in Swift 4.
I have looked at various options but they all relate to v3 and do not work.
Please can someone suggest an example that does so programmatically in Swift 4?
Thank you,
Edit:
I have tried the following examples:
switchTest.transform = CGAffineTransformMakeScale(0.75, 0.75)
switchTest.transform = CGAffineTransform(scaleX: 0.75, y: 0.75)
UISwitch *switchTest = [UISwitch new];
switchTest.transform = CGAffineTransformMakeScale(0.75, 0.75);
The error message that I received is always the same and says this:
Expected declaration
Not possible. A UISwitch has a locked intrinsic height of 51 x 31 . You can force constraints on the switch at design time in the xib... but come runtime it will snap back to its intrinsic size.
The UISwitch class declares a property and a method to control its on/off state. When a person manipulates the switch control (“flips” it), it triggers the valueChanged event. You can customize the appearance of the switch by changing the color used to tint the switch when it's on or off.
Swift 4 Code
Method 1
Drag UISwitch Storyboard. Make an outlet of your UISwitch and replace ViewDidLoad method by this code.
@IBOutlet weak var switchDemo: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
switchDemo.transform = CGAffineTransform(scaleX: 0.75, y: 0.75)
}
Method 2
Make UISwitch through programmatically.
class ViewController: UIViewController {
let switchSwift4 = UISwitch(frame:CGRect(x: 150, y: 300, width: 0, height: 0))
override func viewDidLoad() {
super.viewDidLoad()
self.switchSwift4.isOn = true
switchSwift4.setOn(true, animated: false)
switchSwift4.addTarget(self, action: #selector(switchValueDidChange(_:)), for: .valueChanged)
switchSwift4.transform = CGAffineTransform(scaleX: 0.75, y: 0.75)
self.view!.addSubview(switchSwift4)
}
@objc func switchValueDidChange(_ sender: UISwitch) {
if switchSwift4.isOn == true {
print("On")
}
else {
print("Off")
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With