2021年10月3日日曜日

UITabBarAppearanceを使って、TabBarの配色をセットする

iOS13以降のTabBarのカスタマイズです。
今回の記事では、次のようにTabBarをカスタマイズしました。

1. UITabBarを継承した、カスタムViewを作成する
2. TabBarItemの配色をUITabBarItemAppearanceで作成する
3. UITabBarAppearanceを生成する
4. UITabBarにセットする
5. UITabBarViewControllerにて、カスタムViewを使う


UITabBarを継承した、カスタムViewは次になります。

  1. final class MyUITabBar: UITabBar {
  2.  
  3. override init(frame: CGRect) {
  4. super.init(frame: frame)
  5. setupView()
  6. }
  7. required init?(coder: NSCoder) {
  8. super.init(coder: coder)
  9. setupView()
  10. }
  11.  
  12. private enum Const{
  13. static let backgroundColor: UIColor = .systemGroupedBackground
  14. static let tintColor: UIColor = .gray
  15. static let selectedColor: UIColor = .black
  16. }
  17. private func setupView() {
  18. let tabBarItemAppearance = setupTabBarItemAppearance()
  19. let appearance = UITabBarAppearance()
  20. appearance.configureWithOpaqueBackground()
  21. appearance.backgroundColor = Const.backgroundColor
  22. appearance.stackedLayoutAppearance = tabBarItemAppearance
  23. appearance.inlineLayoutAppearance = tabBarItemAppearance
  24. appearance.compactInlineLayoutAppearance = tabBarItemAppearance
  25.  
  26. standardAppearance = appearance
  27. // iOS15: we need to set
  28. scrollEdgeAppearance = appearance
  29. }
  30.  
  31. private func setupTabBarItemAppearance() -> UITabBarItemAppearance {
  32. let tabBarItemAppearance = UITabBarItemAppearance()
  33. // for normal
  34. tabBarItemAppearance.normal.iconColor = Const.tintColor
  35. tabBarItemAppearance.normal.titleTextAttributes = [NSAttributedString.Key.foregroundColor: Const.tintColor]
  36. // for selected
  37. tabBarItemAppearance.selected.iconColor = Const.selectedColor
  38. tabBarItemAppearance.selected.titleTextAttributes = [NSAttributedString.Key.foregroundColor: Const.selectedColor]
  39. return tabBarItemAppearance
  40. }
  41. }

UITabBarControllerの子となる各ViewControllerでは、次のようにtabBarItemを指定するのみです。
tabBarItemと配色をするAppearanceをコード上で分け、責務が分離できるので非常に見やすいコードとなりました。

  1. final class FirstViewController: UIViewController {
  2.  
  3. override func viewDidLoad() {
  4. super.viewDidLoad()
  5. setupTabBar()
  6. }
  7. override func viewWillAppear(_ animated: Bool) {
  8. super.viewWillAppear(animated)
  9. }
  10.  
  11. private func setupTabBar() {
  12. tabBarItem = UITabBarItem(title: "Home", image: UIImage(systemName: "house"), selectedImage: UIImage(systemName: "house"))
  13. }
  14. }
  15.  
  16. final class SecondViewController: UIViewController {
  17.  
  18. override func viewDidLoad() {
  19. super.viewDidLoad()
  20. setupTabBar()
  21. }
  22. override func viewWillAppear(_ animated: Bool) {
  23. super.viewWillAppear(animated)
  24. }
  25.  
  26. private func setupTabBar() {
  27. tabBarItem = UITabBarItem(title: "Trash", image: UIImage(systemName: "trash"), selectedImage: UIImage(systemName: "trash"))
  28. }
  29.  
  30. }

0 件のコメント:

コメントを投稿