如何在分段控件中更改单个段的颜色

How to change color of single segment in segmented control

我为我的应用程序创建了一个分段控件,它由 4 个部分组成。我知道如何为所有四个更改背景颜色,但我希望每个部分都有自己的颜色:

第 1 段 - 蓝色背景色

第 2 段 - 红色背景色

等等

有什么方法可以在swift中实现吗?

Try below code

func getImageWithColor(color: UIColor, size: CGSize) -> UIImage {
let rect = CGRectMake(0, 0, size.width, size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}

Use below metod for each segment set image (above method give image with color)

setImage(image: UIImage?, forSegmentAtIndex segment: Int) // can only have image or title, not both. must be 0..#segments - 1 (or ignored). default is nil