LoginSignup
8
7

More than 3 years have passed since last update.

iOS13 UISegmentControlのBeforeAfterを見てみる

Posted at

概要

iOS13からUISegmentedControlの見た目と動きが大きく変更になりました。

default.png

これまではButtonが複数あるタブっぽい動きでしたが、UISwitchのような動きに変わりましたね。
iOS13では他の新機能が目立って取り上げられていたので、UIKitの見た目変更があると全く知らなくて
開発中アプリの動作確認をしていたら、激変していてびっくりしました汗
実装する上でも変更点があったので備忘録としてまとめていきます。

変更点

iOS7からはUISegmentControlの色の指定はtintColorでしていましたが、
iOS13以降はこれが使えなく、代わりにselectedSegmentTintColorが追加されました。
機能的には全く同じ。
そう、 プロパティ名が長くなっただけ←

どちらもアプリで対応する場合はavailableを使用してバージョン管理が必要です。

SampleViewController.swift
import UIKit

class SampleViewController: UIViewController
{
    @IBOutlet weak var segmentControl: UISegmentedControl!

    override func viewDidLoad()
    {
        super.viewDidLoad()

        // 背景色
        segmentControl.backgroundColor = .white
        // ベースカラー
        if #available(iOS 13.0, *) {
          segmentControl.selectedSegmentTintColor = .red
        } else {
          segmentControl.tintColor = .red
        }
        // 通常時の文字色
        segmentControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.red], for: .normal)
        // 選択時の文字色
        segmentControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white], for: .selected)
    }
}

colored.png

ちなみに、背景色に白色を指定すると影がついたようなグレーになってしまいます。。
これはそういう仕様のようで色々頑張ってみましたが背景を完全な白にできませんでした。。
どうしてもしたい場合は画像を背景にするしかないのかな?汗

また、iOS12以前のSegmentControlのように外枠をつけてみました。

SampleViewController.swift
// 上記のコードに追記
segmentControl.layer.borderColor = UIColor.red.cgColor
segmentControl.layer.borderWidth = 1
segmentControl.layer.cornerRadius = 4

bordered.png

ちょっと外枠と内側のタブの間に隙間ができるんですね。なるほど。。
iOS12以前のものはパッと見変化がないですが、cornerRadiusの値によって角丸のところが色が固まっているみたいになりました。。
下手に外枠はつけない方が良さそうですかね汗

参考

8
7
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
8
7