Home > front end >  How to change font size for each segment in UISegmentedControl. Swift
How to change font size for each segment in UISegmentedControl. Swift

Time:02-21

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

CodePudding user response:

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

example

  • Related