ナビゲーションバーの背景を画像にしてみました。
画像は下のフリー素材を使っています。
青色のざらざらした紙のテクスチャ素材 | 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] } }
起動すると以下のようにバーの背景が代わります。
もし画像サイズが小さい場合は、画像をリピート描画をしてくれます。
下のように、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 } }