3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

iOS13でSegmentedControlの背景を透明にする方法

Last updated at Posted at 2019-09-28

iOS13でUISegmentedControlの背景を透明にするためには、透明画像を背景にセットする必要がある。

実装方法

UIImage+.swift
import UIKit

extension UIImage {

    public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
        let rect = CGRect(origin: .zero, size: size)
        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
        color.setFill()
        UIRectFill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        guard let cgImage = image?.cgImage else { return nil }
        self.init(cgImage: cgImage)
    }
}
HogeViewController.swift
final class HogeViewController: UIViewController {
    @IBOutlet weak var segmentedControl: UISegmentedControl!

    override func viewDidLoad() {
        super.viewDidLoad()
        setupSegmentedControl()
    }

    private func setupSegmentedControl() {
        let clearColorImage = UIImage(color: .clear, size: CGSize(width: 1, height: 1))
        segmentedControl.setBackgroundImage(clearColorImage, for: .normal, barMetrics: .default)
        segmentedControl.setDividerImage(clearColorImage, forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
    }
}
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?