Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize UISwitch in Swift 4

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

like image 494
user1747021 Avatar asked Dec 31 '17 06:12

user1747021


People also ask

How do I reduce the size of the UISwitch?

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.

How do I use UISwitch Swift?

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.


1 Answers

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")
        }
    }
}
like image 63
Khawar Islam Avatar answered Oct 02 '22 17:10

Khawar Islam