繁体   English   中英

如何更改 UISegmentedControl 中每个段的字体大小。 Swift

[英]How to change font size for each segment in UISegmentedControl. Swift

我可以更改 UISegmentedControll 中每个段的字体大小吗? 我知道我可以改变所有人,但我希望每个部分都有不同的字体大小。 是否可以? 例如,如果我有 3 个段,我希望字体大小为 10、15、20。 谢谢

你不能用字符串作为段来做到这一点,但如果你要使用图像,这是可能的。

首先我们需要一个 function 来将 String 转换成图片。 @NoodleOfDeath在 SO 上的回答提供了一个很好的解决方案,它不涉及使用 UIKit 控件:

extension String {
    func image(withAttributes attributes: [NSAttributedString.Key: Any]? = nil, size: CGSize? = nil) -> UIImage? {
        let size = size ?? (self as NSString).size(withAttributes: attributes)
        return UIGraphicsImageRenderer(size: size).image { _ in
            (self as NSString).draw(in: CGRect(origin: .zero, size: size),
                                    withAttributes: attributes)
        }
    }
}

然后你只需将图像而不是字符串插入到你的 UISegmentedControl 中:

let segmentedControl = UISegmentedControl(items: [
    "Paris".image(withAttributes: [.font: UIFont.systemFont(ofSize: 10)])!,
    "London".image(withAttributes: [.font: UIFont.systemFont(ofSize: 15)])!,
    "Berlin".image(withAttributes: [.font: UIFont.systemFont(ofSize: 20)])!,
])

例子

暂无
暂无

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

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