summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPN/Views/MainButton.swift
blob: 3888ff62379d2a7e537e88599750ba89f301b7b7 (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
68
69
70
71
72
73
//
//  MainButton.swift
//  MullvadVPN
//
//  Created by Jon Petersson on 2024-12-04.
//  Copyright © 2025 Mullvad VPN AB. All rights reserved.
//

import SwiftUI
enum MainButtonImagePosition {
    case leading
    case trailing
}

struct MainButton: View {
    var text: LocalizedStringKey
    var style: MainButtonStyle.Style

    var image: Image?
    var imagePosition: MainButtonImagePosition = .leading
    var action: () -> Void

    @State private var imageHeight: CGFloat = 24.0

    var body: some View {
        Button(action: action, label: {
            ZStack {
                // Centered Text
                Text(text)
                    .lineLimit(nil)
                    .multilineTextAlignment(.center)
                    .if(image != nil) { view in
                        // Reserve space for image if present
                        view.padding(.horizontal, imageHeight)
                    }

                // Image on Leading or Trailing
                HStack {
                    if imagePosition == .leading, let image = image {
                        image
                            .resizable()
                            .scaledToFit()
                            .frame(height: imageHeight)
                            .padding(.leading, 8.0)
                        Spacer()
                    }
                    Spacer()
                    if imagePosition == .trailing, let image = image {
                        Spacer() // Push the text to center
                        image
                            .resizable()
                            .scaledToFit()
                            .frame(height: imageHeight)
                            .padding(.trailing, 8.0)
                    }
                }
            }
        })
        .sizeOfView { size in
            let actualHeight = size.height - 16.0
            let baseHeight = max(actualHeight, 24.0)
            imageHeight = baseHeight * 0.8
        }
        .buttonStyle(MainButtonStyle(style))
        .cornerRadius(UIMetrics.MainButton.cornerRadius)
    }
}

#Preview {
    MainButton(text: "Connect", style: .success) {
        print("Tapped")
    }
}