summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPN/Views/CustomSwitch.swift
blob: 0194d34516da6e09af4279655f8eb21bba90dc59 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//
//  CustomSwitch.swift
//  MullvadVPN
//
//  Created by pronebird on 20/05/2021.
//  Copyright © 2025 Mullvad VPN AB. All rights reserved.
//

import UIKit

class CustomSwitch: UISwitch {
    /// Returns the private `UISwitch` background view
    private var backgroundView: UIView? {
        // Go two levels deep only
        let subviewsToExamine = subviews.flatMap { view -> [UIView] in
            [view] + view.subviews
        }

        // Find the first subview that has background color set.
        let backgroundView = subviewsToExamine.first { subview in
            subview.backgroundColor != nil
        }

        return backgroundView
    }

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

        tintColor = .clear
        onTintColor = .clear
        overrideUserInterfaceStyle = .light

        setAccessibilityIdentifier(.customSwitch)

        updateThumbColor(isOn: isOn, animated: false)

        addTarget(self, action: #selector(valueChanged(_:)), for: .valueChanged)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func setOn(_ on: Bool, animated: Bool) {
        super.setOn(on, animated: animated)

        updateThumbColor(isOn: on, animated: animated)
    }

    private func updateThumbColor(isOn: Bool, animated: Bool) {
        let actions = {
            self.thumbTintColor = isOn ? UIColor.Switch.onThumbColor : UIColor.Switch.offThumbColor
            self.backgroundView?.backgroundColor = .clear
        }

        if animated {
            UIView.animate(withDuration: 0.25, animations: actions)
        } else {
            actions()
        }
    }

    @objc private func valueChanged(_ sender: Any) {
        updateThumbColor(isOn: isOn, animated: true)
    }
}