简体   繁体   English

如何对堆栈视图中的所有标签应用相同的大小?

[英]How to apply same for size for all labels in a stackview?

I have a horizontal stackview filled equally with 3 labels.我有一个水平 stackview,同样填充了 3 个标签。 These labels have set adjustsFontSizeToFitWidth and minimumScaleFactor values set.这些标签已设置adjustsFontSizeToFitWidthminimumScaleFactor值集。 2 labels will have short texts and one may have large text. 2 个标签将有短文本,一个可能有大文本。 Now the large title label's font is reduced automatically and I want the other two labels to automatically update their font size to match the last label font size.现在大标题标签的字体自动缩小,我希望其他两个标签自动更新它们的字体大小以匹配最后的 label 字体大小。 Is it possible?可能吗?

Label1 text - "a" Label1 文字 - “a”

Label2 text - "b" Label2 文字 - “b”

Label3 text - "Something long" Label3 文字 - “有些长”

Now Label3's font looks smaller than Label1 and Label2.现在 Label3 的字体看起来比 Label1 和 Label2 小。

To get the smallest font size, you can use the map .要获得最小的字体大小,您可以使用map Then, you can use the min function to find the minimum font size in the array.然后,您可以使用 min function 来查找数组中的最小字体大小。

Here's an example of how you could do this:这是您如何执行此操作的示例:

        let labels = mainContainer
            .arrangedSubviews
            .compactMap { $0 as? UILabel }

        let newFontsSize = labels.map { label in
            var fontSize = label.font.pointSize
            
            while label.isTruncated {
                fontSize -= 0.25
                label.font = label.font.withSize(fontSize)
            }

            return fontSize
        }

        if let smallestFontSize = newFontsSize.min() {
            labels.forEach { label in
                label.font = label.font.withSize(smallestFontSize)
            }
        }

And the extension:和扩展名:

extension UILabel {
    var isTruncated: Bool {
        frame.width < intrinsicContentSize.width
    }

    var isClipped: Bool {
        frame.height < intrinsicContentSize.height
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM