blob: c825f0f8aa23e837850b0af0a4cec36998301458 (
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
|
//
// InAppPurchaseButton.swift
// MullvadVPN
//
// Created by pronebird on 23/03/2020.
// Copyright © 2025 Mullvad VPN AB. All rights reserved.
//
import Foundation
import UIKit
class InAppPurchaseButton: AppButton {
let activityIndicator = SpinnerActivityIndicatorView(style: .medium)
var isLoading = false {
didSet {
if isLoading {
activityIndicator.startAnimating()
} else {
activityIndicator.stopAnimating()
}
setNeedsLayout()
}
}
init() {
super.init(style: .success)
addSubview(activityIndicator)
// Make sure the buy button scales down the font size to fit the long labels.
// Changing baseline adjustment helps to prevent the text from being misaligned after
// being scaled down.
titleLabel?.adjustsFontSizeToFitWidth = true
titleLabel?.baselineAdjustment = .alignCenters
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
// Calculate the content size after insets
let contentSize = frame
let contentEdgeInsets = configuration?.contentInsets ?? .zero
let finalWidth = contentSize.width - (contentEdgeInsets.leading + contentEdgeInsets.trailing)
let finalHeight = contentSize.height - (contentEdgeInsets.top + contentEdgeInsets.bottom)
let contentRect = CGRect(
origin: frame.origin,
size: CGSize(width: finalWidth, height: finalHeight)
)
self.titleLabel?.frame = getTitleRect(forContentRect: contentRect)
self.activityIndicator.frame = activityIndicatorRect(forContentRect: contentRect)
}
private func getTitleRect(forContentRect contentRect: CGRect) -> CGRect {
var titleRect = titleLabel?.frame ?? .zero
let activityIndicatorRect = activityIndicatorRect(forContentRect: contentRect)
// Adjust the title frame in case if it overlaps the activity indicator
let intersection = titleRect.intersection(activityIndicatorRect)
if !intersection.isNull {
if case .leftToRight = effectiveUserInterfaceLayoutDirection {
titleRect.origin.x = max(contentRect.minX, titleRect.minX - intersection.width)
titleRect.size.width = intersection.minX - titleRect.minX
} else {
titleRect.origin.x = titleRect.minX + intersection.width
titleRect.size.width = min(contentRect.maxX, titleRect.maxX) - intersection.maxX
}
}
return titleRect
}
private func activityIndicatorRect(forContentRect contentRect: CGRect) -> CGRect {
var frame = activityIndicator.frame
if case .leftToRight = effectiveUserInterfaceLayoutDirection {
frame.origin.x = contentRect.maxX - frame.width
} else {
frame.origin.x = contentRect.minX
}
frame.origin.y = contentRect.midY
return frame
}
}
|