Search code examples
swiftnslayoutconstraintuiswitch

Align UISwitch to align to center


My swift code below is trying to get the uisiwtch to appear in the center of the screen. As you can see in my photo below. As You can see in the image below. The switch is taking up only a small part of the upper left of the screen. It does not look good.

pic

var soundSwitch = UISwitch()

NSLayoutConstraint.Activate[(
   soundSwitch.leadingAnchor.constraint(equalTo: map.trailingAnchor, constant: 0),
   soundSwitch.topAnchor.constraint(equalTo: text.bottomAnchor, constant : 0),
   soundSwitch.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1/3, constant: 0),
   soundSwitch.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.07, constant: 0),
 )]

Solution

  • Replace

    soundSwitch.leadingAnchor.constraint(equalTo: map.trailingAnchor, constant: 0),
    

    with

    soundSwitch.centerXAnchor.constraint(equalTo: map.centerXAnchor, constant: 0),
    

    Btw don't forget

    soundSwitch.translatesAutoresizingMaskIntoConstraints = false
    

    Also it's preferred to remove both

    soundSwitch.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1/3, constant: 0),
    soundSwitch.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.07, constant: 0),
    

    As the switch won't scale