简体   繁体   中英

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

can i change font sizes for each segment in UISegmentedControll? I know i can change for all, but i want each segment to have different font size. Is it possible? For example if I have 3 segments I want to have font sizes 10,15,20. Thanks

You can't do that with Strings as segments, but if you were to use Images, it's possible.

First we need a function to convert a String into an image. This answer by @NoodleOfDeath on SO gives a nice solution that doesn't involve usage of UIKit controls:

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)
        }
    }
}

Then you simply insert images into your UISegmentedControl instead of Strings:

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)])!,
])

例子

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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