今天要來講最後也是我覺得在開發上比較實用App設定。
1.當我們想設定我的的navagationBar的時候,都要在每個畫面設定背景顏色、等等一些瑣碎的東西,或是你要設定推到下一個VC,簡單說就是透過今天的教學可以讓妳的code看起來更簡潔。
所以,第一步我們要建立一個swift檔案
建立完成後檔名我是叫做BaseViewController,這時候記得import UIKit喔~
然後下面就是我自己的客製化navagationBar的code,可以參考一下~
public func setNavigationBarStyle(){
if #available(iOS 15.0, *) {
let appearance = UINavigationBarAppearance()
appearance.configureWithOpaqueBackground()
appearance.backgroundColor = #colorLiteral(red: 0.7579411864, green: 0.05860135704, blue: 0.1392720342, alpha: 1)
self.navigationController?.navigationBar.tintColor = #colorLiteral(red: 0.9953911901, green: 0.9881951213, blue: 1, alpha: 1)
appearance.titleTextAttributes = [NSAttributedString.Key.foregroundColor : #colorLiteral(red: 0.9953911901, green: 0.9881951213, blue: 1, alpha: 1)]
self.navigationController?.navigationBar.standardAppearance = appearance
self.navigationController?.navigationBar.scrollEdgeAppearance = self.navigationController?.navigationBar.standardAppearance
} else {
self.navigationController?.navigationBar.barTintColor = #colorLiteral(red: 0.7579411864, green: 0.05860135704, blue: 0.1392720342, alpha: 1)
self.navigationController?.navigationBar.tintColor = #colorLiteral(red: 0.9953911901, green: 0.9881951213, blue: 1, alpha: 1)
self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor : #colorLiteral(red: 0.9953911901, green: 0.9881951213, blue: 1, alpha: 1)]
}
}
if #available(iOS 15.0),是因為iOS15之後navagationBar會有高度顯示異常問題,所以就把這段加進去~
其他的設定應該不難,看不懂的話就動動手指google一下就行了。
呼叫方法:
之前有提到class可以被繼承,所以把原本的UIViewController改成我們的BaseViewController,再去call裡面的func就可以了~
然後這裡是pushVC的func,也是比較簡單的寫法,可以參考一下
public func pushViewController(vc: UIViewController, animated: Bool = true) {
vc.hidesBottomBarWhenPushed = true
if let navigationController = UIApplication.shared.keyWindow?.rootViewController as? UINavigationController {
navigationController.pushViewController(vc, animated: animated)
}
}
public func pushViewController(inStack stack: [UIViewController], vc: UIViewController, animated: Bool = true) {
var stack = stack
vc.hidesBottomBarWhenPushed = true
stack.append(vc)
self.navigationController?.setViewControllers(stack, animated: animated)
// self.navigationController?.pushViewController(vc, animated: animated)
}
public func popViewController(_ animated: Bool = true) {
self.navigationController?.popViewController(animated: animated)
}
public func popToRootViewController(_ animated: Bool = true) {
self.navigationController?.popToRootViewController(animated: animated)
}
public func dismissViewController(_ animated: Bool = true, completion: (()-> Void)? = nil) {
self.navigationController?.dismiss(animated: animated, completion: completion)
}