Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

place text inside UISwitch in swift 4

Tags:

ios

swift

After 2 days try, I'm posting this question here. I need to achieve this enter image description here

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.

like image 290
Ripa Saha Avatar asked Jun 03 '19 10:06

Ripa Saha


3 Answers

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

like image 59
Dharmesh Kheni Avatar answered Oct 02 '22 07:10

Dharmesh Kheni


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
}
like image 24
NEEL PATEL Avatar answered Oct 02 '22 07:10

NEEL PATEL


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.

like image 28
Blazej SLEBODA Avatar answered Oct 02 '22 09:10

Blazej SLEBODA