summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPN/Views/LinkButton.swift
blob: bf261553fa5ed12796987a1997ea36269d7e9890 (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
//
//  LinkButton.swift
//  MullvadVPN
//
//  Created by Jon Petersson on 2023-12-20.
//  Copyright © 2025 Mullvad VPN AB. All rights reserved.
//

import UIKit

/// A subclass that implements the button that visually look like URL links on the web
class LinkButton: CustomButton {
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

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

    var titleString: String? {
        didSet {
            updateAttributedTitle(string: titleString)
        }
    }

    private func commonInit() {
        imageAlignment = .trailing
        contentHorizontalAlignment = .leading
        configuration?.contentInsets = .zero
        accessibilityTraits.insert(.link)
    }

    private func updateAttributedTitle(string: String?) {
        let states: [UIControl.State] = [.normal, .highlighted, .disabled]
        states.forEach { state in
            let attributedTitle = string.flatMap { makeAttributedTitle($0, for: state) }
            self.setAttributedTitle(attributedTitle, for: state)
        }
    }

    private func makeAttributedTitle(
        _ title: String,
        for state: UIControl.State
    ) -> NSAttributedString {
        var attributes: [NSAttributedString.Key: Any] = [
            .underlineStyle: NSUnderlineStyle.single.rawValue
        ]

        if let titleColor = state.customButtonTitleColor {
            attributes[.foregroundColor] = titleColor
        }

        return NSAttributedString(string: title, attributes: attributes)
    }
}