NetNewsWire/iOS/Timeline/Cell/SingleLineUILabelSizer.swift
2024-05-03 22:49:27 -07:00

65 lines
1.4 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// SingleLineUILabelSizer.swift
// NetNewsWire
//
// Created by Brent Simmons on 2/19/18.
// Copyright © 2018 Ranchero Software. All rights reserved.
//
import UIKit
// Get the size of an UILabel configured with a specific font with a specific size.
// Uses a cache.
// Main thready only.
@MainActor final class SingleLineUILabelSizer {
let font: UIFont
private var cache = [String: CGSize]()
init(font: UIFont) {
self.font = font
}
func size(for text: String) -> CGSize {
if let cachedSize = cache[text] {
return cachedSize
}
let height = text.height(withConstrainedWidth: .greatestFiniteMagnitude, font: font)
let width = text.width(withConstrainedHeight: .greatestFiniteMagnitude, font: font)
let calculatedSize = CGSize(width: ceil(width), height: ceil(height))
cache[text] = calculatedSize
return calculatedSize
}
@MainActor static private var sizers = [UIFont: SingleLineUILabelSizer]()
static func sizer(for font: UIFont) -> SingleLineUILabelSizer {
if let cachedSizer = sizers[font] {
return cachedSizer
}
let newSizer = SingleLineUILabelSizer(font: font)
sizers[font] = newSizer
return newSizer
}
// Use this call. Its easiest.
static func size(for text: String, font: UIFont) -> CGSize {
return sizer(for: font).size(for: text)
}
static func emptyCache() {
sizers = [UIFont: SingleLineUILabelSizer]()
}
}