From 4df1a5cd6bb1e7d6baba012ed5675f1fcfc19ea0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roberto=20Go=CC=81mez?= Date: Wed, 25 Jan 2023 16:02:51 +0100 Subject: [PATCH] iOS-6850: Calculate the right size to fit the badge label depending on its text --- .../Utils/Shared Views/Views/BadgeButton.swift | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/iMEGA/Utils/Shared Views/Views/BadgeButton.swift b/iMEGA/Utils/Shared Views/Views/BadgeButton.swift index a0c99eb1df..21595f6772 100644 --- a/iMEGA/Utils/Shared Views/Views/BadgeButton.swift +++ b/iMEGA/Utils/Shared Views/Views/BadgeButton.swift @@ -30,19 +30,20 @@ final class BadgeButton: UIButton { badgeLabel?.isHidden = false badgeLabel?.text = text badgeLabel?.font = UIFont.boldSystemFont(ofSize: 12.0) - badgeLabel?.edgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4) + badgeLabel?.edgeInsets = UIEdgeInsets(top: 4, left: 2, bottom: 4, right: 2) badgeLabel?.layer.cornerRadius = 10 accessibilityValue = Strings.Localizable.notifications + + if let badgeLabel { + badgeLabel.widthAnchor.constraint(greaterThanOrEqualToConstant: calculateWidthThatFits(label: badgeLabel)).isActive = true + } } // MARK: - Privates private func layoutBadgeLabel(_ badgeLabel: UILabel) { badgeLabel.translatesAutoresizingMaskIntoConstraints = false - NSLayoutConstraint.activate([ - badgeLabel.widthAnchor.constraint(greaterThanOrEqualToConstant: 20), - badgeLabel.heightAnchor.constraint(equalToConstant: 20) - ]) + badgeLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true } private func setupBadgeLabel(with trait: UITraitCollection) -> UILabel { @@ -72,4 +73,11 @@ final class BadgeButton: UIButton { badgeLabel.centerXAnchor.constraint(equalTo: trailingAnchor) ]) } + + private func calculateWidthThatFits(label: UILabel) -> CGFloat { + let minimumWidth: CGFloat = 20 + let fitSize = CGSize(width: UIScreen.main.bounds.width, height: .greatestFiniteMagnitude) + let fitWidth = label.sizeThatFits(fitSize).width + return fitWidth > minimumWidth ? fitWidth : minimumWidth + } }