LoginSignup
5
1

More than 3 years have passed since last update.

Xcode11のUISegmentedControlにつまずいた

Last updated at Posted at 2019-12-13

はじめに

もうネタがない...(リリースノートを漁る日々)

Xcode リリースノートで下記のようんものを発見:joy_cat:

Setting the Selected Segment Tint Color of a segmented control in Interface Builder to a named color will cause a failure when the view is loaded on iOS 12 and earlier. (55254963)

UISegmentedControl で iOS13 から追加された selectedSegmentTintColor に Storyboard,xib 上で Color Asset で作成した色を設定すると iOS13 未満でクラッシュする模様。

Xcode11.3 では修正されたようです:innocent:

検証

とりあえず検証してみました。Storyboard で selectedSegmentTintColor に Color Asset の色を設定して iOS12 で実行!!すると下記のようなエラーが出てクラッシュしました:joy_cat:

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key selectedSegmentTintColor.'

よくみる UndefinedKey ですね。。。

対応

対応は下記2パターンかと思います。

  • Storyboard で selectedSegmentTintColor に Custom Color を設定する
    Color Asset の色で設定するのはあきらめる方法です。
  • コードで selectedSegmentTintColor に Color Asset の色を設定する
    Storyboard では selectedSegmentTintColor に色を設定せずコード上で下記のように設定する方法です。
@IBOutlet private weak var segmentedControl: UISegmentedControl! {
  didSet {
    if #available(iOS 13.0, *) {
      segmentedControl.selectedSegmentTintColor = UIColor(named: "Color")
    } 
  }
}

これで iOS13, iOS12 でもクラッシュせずに表示できるようになりました!!!

UISegmentedControl の色について

とりあえずクラッシュしないようになりましたが UISegmentedControl の色を iOS12, 13 である程度統一させようと思うと色々工夫しないといけないようです。

参考

selectedSegmentTintColor を設定

Storyboard で selectedSegmentTintColor に色を設定するだけだと下記のようになります。

iOS12 iOS13 Light iOS13 Dark
tint_color_default 13_light 13_dark

selectedSegmentTintColor & tintColor を設定

Storyboard で tintColor も色を設定してみる

iOS12 iOS13 Light iOS13 Dark
tint_color 13_light 13_dark

ちょっとダークモードの未選択の方がみずらい気がしますが、許容範囲な気も...

Color Asset の色を使いたい場合は下記のような感じ

@IBOutlet private weak var segmentedControl: UISegmentedControl! {
  didSet {
    if #available(iOS 13.0, *) {
      segmentedControl.selectedSegmentTintColor = UIColor(named: "Color")
    } else {
      segmentedControl.tintColor = UIColor(named: "Color") // こっちはstoryboardでも可
    }
  }
}

その他

その他にも UISegmentedControl は iOS13 で変更されている部分があるそうです。

背景画像を設定していっても角丸処理が入り角が切り取られるんだとか。

さいごに

UISegmentedControl は iOS13 で色々変更があったようですが、私はあまり使っていなかったのでほぼ影響ありませんでした:expressionless:

参考

5
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
5
1