0
0

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 1 year has passed since last update.

UITabBarについてのメモ

Posted at

SwiftでUITabBarのアイコン選択時にアイコンの色と大きさの変更、タイトルを太字にする方法

1. UITabBarControllerDelegateをクラス宣言に追加する。
→UITabBarのアイテムが選択されたときに通知を受け取ることができるようになる。

class ViewController: UIViewController, UITabBarControllerDelegate {
}

2. UITabBarControllerDelegateのメソッドtabBarController(_:didSelect:)を実装する。
このメソッドは、タブバーのアイテムが選択されたときに呼び出される。

class ViewController: UIViewController, UITabBarControllerDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // UITabBarControllerのdelegateを設定
        tabBarController?.delegate = self
    }
    
    func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        // 選択されたタブのインデックスを取得
        if let selectedIndex = tabBarController.viewControllers?.firstIndex(of: viewController) {
            // タブバーのアイテムを取得
            if let tabBarItem = tabBarController.tabBar.items?[selectedIndex] {
                // 選択時のアイコンの色を変える
                tabBarItem.selectedImage = tabBarItem.selectedImage?.withTintColor(.red)
                
                // アイコンのサイズを変更
                let iconSize = CGSize(width: 30, height: 30) // 好みのサイズに変更してください
                tabBarItem.selectedImage = tabBarItem.selectedImage?.scaled(to: iconSize)
                
                // タイトルを太字にする
                tabBarItem.setTitleTextAttributes([NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 12)], for: .selected)
            }
        }
    }
}

extension UIImage {
    func scaled(to size: CGSize) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
        defer { UIGraphicsEndImageContext() }
        draw(in: CGRect(origin: .zero, size: size))
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}
  • tabBarController(_:didSelect:)・・・選択されたタブのインデックスを取得し、対応するタブバーのアイテムを変更している。

  • tabBarItem.selectedImage = tabBarItem.selectedImage?.withTintColor(.red)・・・アイコンの色を変更。ここでは赤色に変更している。

  • tabBarItem.selectedImage = tabBarItem.selectedImage?.scaled(to: iconSize)・・・アイコンのサイズを変更。iconSize変数で指定したサイズに変更している。

  • tabBarItem.setTitleTextAttributes([NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 12)], for: .selected)・・・タイトルを太字にしている。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?