-
Notifications
You must be signed in to change notification settings - Fork 384
/
Copy pathAlertViewController.swift
319 lines (250 loc) · 10.4 KB
/
AlertViewController.swift
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
//
// AlertViewController.swift
// MullvadVPN
//
// Created by Jon Petersson on 2023-05-19.
// Copyright © 2023 Mullvad VPN AB. All rights reserved.
//
import UIKit
enum AlertActionStyle {
case `default`
case destructive
fileprivate var buttonStyle: AppButton.Style {
switch self {
case .default:
return .default
case .destructive:
return .danger
}
}
}
enum AlertIcon {
case alert
case warning
case info
case spinner
fileprivate var image: UIImage? {
switch self {
case .alert:
return UIImage(named: "IconAlert")?.withTintColor(.dangerColor)
case .warning:
return UIImage(named: "IconAlert")?.withTintColor(.white)
case .info:
return UIImage(named: "IconInfo")?.withTintColor(.white)
default:
return nil
}
}
}
class AlertViewController: UIViewController {
typealias Handler = () -> Void
var onDismiss: Handler?
private let scrollView = UIScrollView()
private var scrollViewHeightConstraint: NSLayoutConstraint!
private let presentation: AlertPresentation
private let viewContainer: UIView = {
let view = UIView()
view.backgroundColor = .secondaryColor
view.layer.cornerRadius = 11
return view
}()
private let buttonView: UIStackView = {
let view = UIStackView()
view.axis = .vertical
view.spacing = UIMetrics.CustomAlert.containerSpacing
view.isLayoutMarginsRelativeArrangement = true
view.directionalLayoutMargins = UIMetrics.CustomAlert.containerMargins
return view
}()
private let contentView: UIStackView = {
let view = UIStackView()
view.axis = .vertical
view.spacing = UIMetrics.CustomAlert.containerSpacing
view.isLayoutMarginsRelativeArrangement = true
view.directionalLayoutMargins = UIMetrics.CustomAlert.containerMargins
return view
}()
private var handlers = [UIButton: Handler]()
init(presentation: AlertPresentation) {
self.presentation = presentation
super.init(nibName: nil, bundle: nil)
modalPresentationStyle = .overFullScreen
modalTransitionStyle = .crossDissolve
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
view.layoutIfNeeded()
scrollViewHeightConstraint.constant = scrollView.contentSize.height
adjustButtonMargins()
}
override func viewDidLoad() {
super.viewDidLoad()
view.accessibilityIdentifier = presentation.accessibilityIdentifier ?? .alertContainerView
view.backgroundColor = .black.withAlphaComponent(0.5)
setContent()
setConstraints()
}
private func setContent() {
presentation.icon.flatMap { addIcon($0) }
presentation.header.flatMap { addHeader($0) }
presentation.title.flatMap { addTitle($0) }
if let message = presentation.attributedMessage {
addMessage(message)
} else if let message = presentation.message {
addMessage(message)
}
presentation.buttons.forEach { action in
addAction(
title: action.title,
style: action.style,
accessibilityId: action.accessibilityId,
handler: action.handler
)
}
// Icon only spinner alerts should have no background and equal top and bottom margins.
if presentation.icon == .spinner, contentView.arrangedSubviews.count == 1 {
viewContainer.backgroundColor = .clear
contentView.directionalLayoutMargins.bottom = UIMetrics.CustomAlert.containerMargins.top
}
}
private func setConstraints() {
viewContainer.addConstrainedSubviews([scrollView, buttonView]) {
scrollView.pinEdgesToSuperview(.all().excluding(.bottom))
buttonView.pinEdgesToSuperview(.all().excluding(.top))
buttonView.topAnchor.constraint(equalTo: scrollView.bottomAnchor)
}
scrollView.addConstrainedSubviews([contentView]) {
contentView.pinEdgesToSuperview(.all())
contentView.widthAnchor.constraint(equalTo: scrollView.widthAnchor)
}
scrollViewHeightConstraint = scrollView.heightAnchor.constraint(equalToConstant: 0).withPriority(.defaultLow)
scrollViewHeightConstraint.isActive = true
view.addConstrainedSubviews([viewContainer]) {
viewContainer.centerXAnchor.constraint(equalTo: view.centerXAnchor)
viewContainer.centerYAnchor.constraint(equalTo: view.centerYAnchor)
viewContainer.topAnchor
.constraint(greaterThanOrEqualTo: view.layoutMarginsGuide.topAnchor)
.withPriority(.defaultHigh)
view.layoutMarginsGuide.bottomAnchor
.constraint(greaterThanOrEqualTo: viewContainer.bottomAnchor)
.withPriority(.defaultHigh)
let leadingConstraint = viewContainer.leadingAnchor
.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor)
let trailingConstraint = view.layoutMarginsGuide.trailingAnchor
.constraint(equalTo: viewContainer.trailingAnchor)
if traitCollection.userInterfaceIdiom == .pad {
viewContainer.widthAnchor
.constraint(lessThanOrEqualToConstant: UIMetrics.preferredFormSheetContentSize.width)
leadingConstraint.withPriority(.defaultHigh)
trailingConstraint.withPriority(.defaultHigh)
} else {
leadingConstraint
trailingConstraint
}
}
}
private func adjustButtonMargins() {
if !buttonView.arrangedSubviews.isEmpty {
// The presence of a button should yield a custom top margin.
buttonView.directionalLayoutMargins.top = UIMetrics.CustomAlert.interContainerSpacing
// Buttons below scrollable content should have more margin.
if scrollView.contentSize.height > scrollView.bounds.size.height {
buttonView.directionalLayoutMargins.top = UIMetrics.CustomAlert.containerSpacing
}
}
}
private func addHeader(_ title: String) {
let label = UILabel()
label.text = title
label.font = .preferredFont(forTextStyle: .largeTitle, weight: .bold)
label.textColor = .white
label.adjustsFontForContentSizeCategory = true
label.textAlignment = .center
label.numberOfLines = 0
label.accessibilityIdentifier = .alertTitle
contentView.addArrangedSubview(label)
contentView.setCustomSpacing(16, after: label)
}
private func addTitle(_ title: String) {
let label = UILabel()
label.text = title
label.font = .preferredFont(forTextStyle: .title3, weight: .semibold)
label.textColor = .white.withAlphaComponent(0.9)
label.adjustsFontForContentSizeCategory = true
label.numberOfLines = 0
contentView.addArrangedSubview(label)
contentView.setCustomSpacing(8, after: label)
}
private func addMessage(_ message: String) {
let label = UILabel()
let message = NSMutableAttributedString(string: message)
message.apply(paragraphStyle: .alert)
label.attributedText = message
label.font = .preferredFont(forTextStyle: .body)
label.textColor = .white.withAlphaComponent(0.8)
label.adjustsFontForContentSizeCategory = true
label.numberOfLines = 0
contentView.addArrangedSubview(label)
}
private func addMessage(_ message: NSAttributedString) {
let label = UILabel()
let message = NSMutableAttributedString(attributedString: message)
message.removeAttribute(.paragraphStyle, range: NSRange(location: 0, length: message.length))
message.apply(paragraphStyle: .alert)
label.attributedText = message
label.textColor = .white.withAlphaComponent(0.8)
label.adjustsFontForContentSizeCategory = true
label.numberOfLines = 0
contentView.addArrangedSubview(label)
}
private func addIcon(_ icon: AlertIcon) {
let iconView = icon == .spinner ? getSpinnerView() : getImageView(for: icon)
contentView.addArrangedSubview(iconView)
}
private func addAction(
title: String,
style: AlertActionStyle,
accessibilityId: AccessibilityIdentifier?,
handler: (() -> Void)? = nil
) {
let button = AppButton(style: style.buttonStyle)
button.setTitle(title, for: .normal)
button.accessibilityIdentifier = accessibilityId
button.addTarget(self, action: #selector(didTapButton), for: .touchUpInside)
buttonView.addArrangedSubview(button)
handler.flatMap { handlers[button] = $0 }
}
private func getImageView(for icon: AlertIcon) -> UIView {
let imageView = UIImageView()
let imageContainerView = UIView()
imageContainerView.addConstrainedSubviews([imageView]) {
imageView.pinEdges(.init([.top(0), .bottom(0)]), to: imageContainerView)
imageView.centerXAnchor.constraint(equalTo: imageContainerView.centerXAnchor, constant: 0)
imageView.heightAnchor.constraint(equalToConstant: 44)
imageView.widthAnchor.constraint(equalTo: imageView.heightAnchor, multiplier: 1)
}
imageView.image = icon.image?.withRenderingMode(.alwaysOriginal)
imageView.contentMode = .scaleAspectFit
return imageContainerView
}
private func getSpinnerView() -> UIView {
let spinnerView = SpinnerActivityIndicatorView(style: .large)
let spinnerContainerView = UIView()
spinnerContainerView.addConstrainedSubviews([spinnerView]) {
spinnerView.pinEdges(.init([.top(0), .bottom(0)]), to: spinnerContainerView)
spinnerView.centerXAnchor.constraint(equalTo: spinnerContainerView.centerXAnchor, constant: 0)
}
spinnerView.startAnimating()
return spinnerContainerView
}
@objc private func didTapButton(_ button: AppButton) {
if let handler = handlers.removeValue(forKey: button) {
handler()
}
handlers.removeAll()
onDismiss?()
}
}