2016-10-08 4 views
24

Я пытаюсь изменить цвет панели навигации, но обнаружил, что это невозможно, только если навигатор является корневым.Swift - iOS: изменение цвета панели навигации

Я пытаюсь это:

self.navigationController?.navigationBar.translucent = true 

self.navigationController!.navigationBar.barTintColor = UIColor.blueColor() 

Все мои Viewcontrollers связаны с контроллерами штурмана. Однако ничего не изменилось. На самом деле я пытался сделать то же самое из раскадровки, но это работает, только если я в первом навигаторе.

Я пытался читать все, что связано с этой проблемой, но ничего не нашли

Я мог бы добавить любой элемент на панель навигатора, как этот

let HomeImage = UIImage(named: "home")! 
    let Home : UIBarButtonItem = UIBarButtonItem(image: HomeImage, style: .Plain, target: self, action: "home:") 
    navigationItem.rightBarButtonItem = Home 

ответ

56

На самом деле, я обнаружил, что решение было использовать в appdelegate.siwft:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 
    // Override point for customization after application launch. 
    UINavigationBar.appearance().barTintColor = UIColor(red: 0, green: 0/255, blue: 205/255, alpha: 1) 
    UINavigationBar.appearance().tintColor = UIColor.whiteColor() 
    UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor()] 

    return true 
} 

, а затем в каждом контроллере представления , что нам нужен другой цвет фона или что-то еще

  1. переход должен быть отводящий, чем "шоу"

  2. использовать Func viewWillAppear

    override func viewWillAppear(animated: Bool) { 
    super.viewWillAppear(animated) 
    self.navigationController?.navigationBar.barTintColor = UIColor.whiteColor() 
    self.navigationController?.navigationBar.tintColor = UIColor.blueColor() 
    self.navigationController!.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.blueColor()] 
    

    }

+0

Это хорошо работает с стручка Eureka –

4

Для изменения панели навигации цвет темы в течение полного приложения вы может сделать это, используя внешний вид UiNavigation.

UINavigationBar.appearance().barTintColor = UIColor.redColor() 
1

Если ваш контроллер представления встроен в контроллер навигации, то вы можете удалить эту навигацию по умолчанию панель и может использовать пользовательские панели навигации для этого вида контроллера.

Тогда вы можете сделать выглядеть

UINavigationBar.appearance().barTintColor = UIColor(red: 46.0/255.0, green: 14.0/255.0, blue: 74.0/255.0, alpha: 1.0) 
0
self.navigationController.navigationBar.barTintColor = [UIColor blackColor]; 
4

Swift 4.x:

//To change Navigation Bar Background Color 
    UINavigationBar.appearance().barTintColor = UIColor.blue 
    //To change Back button title & icon color 
    UINavigationBar.appearance().tintColor = UIColor.white 
    //To change Navigation Bar Title Color 
    UINavigationBar.appearance().titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white] 

Swift 3.x:

//To change Navigation Bar Background Color 
UINavigationBar.appearance().barTintColor = UIColor.blue 
//To change Back button title & icon color 
UINavigationBar.appearance().tintColor = UIColor.white 
//To change Navigation Bar Title Color 
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white] 
28

Обновление для Swift 3

// setup navBar..... 
    UINavigationBar.appearance().barTintColor = .black 
    UINavigationBar.appearance().tintColor = .white 
    UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white] 
    UINavigationBar.appearance().isTranslucent = false 

Swift 4

UINavigationBar.appearance().barTintColor = .black 
    UINavigationBar.appearance().tintColor = .white 
    UINavigationBar.appearance().titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white] 
    UINavigationBar.appearance().isTranslucent = false 
+0

сделать я должен сделать это в файле appdelegate.siwft? – TheSwiftGuy77

+0

FUNC приложение (_ аппликации: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Любой]?) -> Bool { // установка NavBar ..... } – iajmeri43

+0

@PrashannaChudal да, и может .. код это выше AppDelegate метод (см. выше комментарий) .. – iajmeri43

4

сделать следующее обновление файла AppDelegate.Swift т.е. UINavigationBar.appearance() .barTintColor = UIColor (красный: x.xx, зеленый: x.xx, синий: x.xx, alph а: 1.0)

Обратитесь к примеру ниже

импорта UIKit

@UIApplicationMain класса AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow? 


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 
    // Override point for customization after application launch. 
    UINavigationBar.appearance().barTintColor = UIColor(red:0.03, green:0.25, blue:0.11, alpha:1.0) 
    UINavigationBar.appearance().tintColor = UIColor.white 
    UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white] 
    return true 
} 

func applicationWillResignActive(_ application: UIApplication) { 
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. 
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. 
} 

func applicationDidEnterBackground(_ application: UIApplication) { 
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 
} 

func applicationWillEnterForeground(_ application: UIApplication) { 
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. 
} 

func applicationDidBecomeActive(_ application: UIApplication) { 
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 
} 

func applicationWillTerminate(_ application: UIApplication) { 
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 
} 

}

Смежные вопросы