Bugrym
Bugrym

Reputation: 85

How to fit a thumb to custom size switch?

I'm working on the custom UISwitch. I have changed size using this: self.transform = CGAffineTransform(scaleX: 1.25, y: 1.16). And now I have one problem, the thumb is still default size. enter image description here

How can I fit it with uiswitch?

class CustomSwitch:UISwitch {

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.viewDidLoad()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        self.viewDidLoad()
    }

    func viewDidLoad() {
        self.transform = CGAffineTransform(scaleX: 1.25, y: 1.16)
        self.setupAppearance()
        self.setColors()
        self.addTarget(self, action: #selector(toggleState), for: .valueChanged)
    }

    func setupAppearance() {
        self.layer.borderColor = UIColor.HavelockBlue.cgColor
        self.layer.borderWidth = 1.0
        self.layer.cornerRadius = self.bounds.height / 2
    }

    func setColors() {
        self.backgroundColor = .white
        self.subviews.first?.subviews.first?.backgroundColor = .clear
        self.onTintColor = .white
        self.thumbTintColor = .HavelockBlue
    }

    @objc func toggleState() {
        if self.isOn {
            print("Dark mode is on")
        } else {
            print("Dark mode is off")
        }
    }
}

Upvotes: 0

Views: 981

Answers (1)

vpoltave
vpoltave

Reputation: 1770

Your problem is, you settings constrained width and height for your custom UISwitch, and after then you are trying to transform this object, but what actually happen.

Inside this override init(frame: CGRect) and required init?(coder: NSCoder) methods if you using auto layout you don't have actually final size of your UIView, the size is taken from IB. But you are setting self.layer.cornerRadius = self.bounds.height / 2. If you will print values of frame.size and bounds.size you will see.

Simple solution is to remove constrained sizes from IB and just transform to your desire scale.


Example:

required init?(coder: NSCoder) {
    super.init(coder: coder)
    changeSwitchSize()
}

override init(frame: CGRect) {
    super.init(frame: frame)
    changeSwitchSize()
}

private func changeSwitchSize() {
    print("Before transform switch frame size: \(frame.size), bounds size: \(bounds.size)")
    self.transform = CGAffineTransform(scaleX: 1.25, y: 1.16)
    print("After transform switch frame size: \(frame.size), bounds size: \(bounds.size)")
}

/// Before transform switch frame: (51.0, 31.0), (51.0, 31.0)
/// After transform switch frame: (63.75, 35.95999999999998), (51.0, 31.0)

But be aware than CGAffineTransform change view's frame relative to its superview

More about it: https://stackoverflow.com/a/11288488/6057764

Upvotes: 1

Related Questions