Ripa Saha
Ripa Saha

Reputation: 2540

place text inside UISwitch in swift 4

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.

Upvotes: 7

Views: 7661

Answers (3)

Blazej SLEBODA
Blazej SLEBODA

Reputation: 9925

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.

Upvotes: 2

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71852

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

Upvotes: 6

NEEL PATEL
NEEL PATEL

Reputation: 11

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
}

Upvotes: 1

Related Questions