After 2 days try, I'm posting this question here. I need to achieve this
in swift 4. I've tried below:-
let switchOnOff = UISwitch(frame:CGRect(x: 150, y: 150, width: 200, height: 0))
switchOnOff.addTarget(self, action: #selector(self.switchStateDidChange), for: .valueChanged)
switchOnOff.setOn(true, animated: false)
self.view.addSubview(switchOnOff)
@objc func switchStateDidChange(sender:UISwitch){
if (sender.isOn == true){
sender.setOn(true, animated: false)
//sender.onImage = UIImage(named: "edit.png")
}
else{
sender.setOn(false, animated: false)
//sender.offImage = UIImage(named: "offSwitch.png")
}
}
sender.onImage , sender.offImage not working in this ios 10+ version.
Then I tried to use sender.tag
, sender.text
These are also not working. Not getting any proper help in googling. So please help me if You already solved this matter.
Thanks Guys.
With default UISwitch
you can not achieve it because it doesn't provide this much customisation. But here is third party lib LabelSwitch which provide same customise you needed and it will look like:
enter image description here here I am using button go to button property inspector
set the "State config" have option 1) default 3) selected 1)select "Default" and set image for default button image 2)select "selected" set the image for selected button image here my button name is "LocaionOnOffSwiftch"
button action try this code
@IBAction func BtnLocationOnOffSwiftch(_ sender: UIButton) {
LocaionOnOffSwiftch.isSelected = !LocaionOnOffSwiftch.isSelected
}
Xcode 12 comes with a new property title on UISwitch type but it is only available for checkbox styled switches on Mac (iOS Catalyst), not on iOS.
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