しめ鯖日記

swift, iPhoneアプリ開発, ruby on rails等のTipsや入門記事書いてます

【iOS】ナビゲーションバーの背景を画像にする

ナビゲーションバーの背景を画像にしてみました。

f:id:llcc:20170818121811p:plain

画像は下のフリー素材を使っています。

青色のざらざらした紙のテクスチャ素材 | Paper-co | 紙のテクスチャー素材を無料でダウンロードできるサイト

バーに背景画像を設定する方法は下の通りです。
titleTextAttributesはタイトルの色を白くする為の設定です。

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationController?.navigationBar.setBackgroundImage(UIImage(named: "texture"), for: .default)
        navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white]
    }
}

起動すると以下のようにバーの背景が代わります。
もし画像サイズが小さい場合は、画像をリピート描画をしてくれます。

f:id:llcc:20170818121817p:plain

下のように、UIImageをUIColorに変換した上でbarTintColorに設定しても同様の結果になります。

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationController?.navigationBar.barTintColor = UIColor(patternImage: UIImage(named: "texture")!)
    }
}

アプリ内の全てのナビゲーションバーの背景を変える場合は、以下のようにappearanceを使います。

ちなみにbarTintColorで画像をセットしている時にSafariViewControllerを使うと'NSInternalInconsistencyException', reason: 'Only RGBA or White color spaces are supported in this situation.'というエラーでクラッシュします。
SafariViewController以外でもエラーになるかもしれないので、できるだけsetBackgroundImageを使う方が安全そうです。

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        UINavigationBar.appearance().barTintColor = UIColor(patternImage: UIImage(named: "texture")!)
        
        return true
    }
}