How to change the colors of a segment in a UISegmentedControl in iOS 13?

前端 未结 14 835
醉话见心
醉话见心 2020-11-30 18:13

A UISegmentedControl has a new appearance in iOS 13 and existing code to alter the colors of the segmented control no longer work as they did.

Prior to

14条回答
  •  春和景丽
    2020-11-30 18:37

    If you want to set the background to clear you have to do this:

    if #available(iOS 13.0, *) {
      let image = UIImage()
      let size = CGSize(width: 1, height: segmentedControl.intrinsicContentSize.height)
      UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
      image.draw(in: CGRect(origin: .zero, size: size))
      let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
      UIGraphicsEndImageContext()
      segmentedControl.setBackgroundImage(scaledImage, for: .normal, barMetrics: .default)
      segmentedControl.setDividerImage(scaledImage, forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
    }
    

提交回复
热议问题