要在单个文件中自定义NavigationBar,您可以使用SwiftUI或者UIKit
使用SwiftUI:
CustomNavigationBar.swift
。import SwiftUI
struct CustomNavigationBar: View {
var title: String
var body: some View {
VStack {
HStack {
Button(action: {
// 返回按钮操作
}) {
Image(systemName: "arrow.backward")
.foregroundColor(.white)
.font(.system(size: 20))
}
Text(title)
.foregroundColor(.white)
.font(.system(size: 24))
.bold()
Spacer()
}
.padding(.horizontal, 16)
.frame(height: 60)
.background(Color.blue)
}
}
}
CustomNavigationBar
:import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
VStack {
CustomNavigationBar(title: "My Custom Navigation")
Text("Hello, World!")
.padding()
}
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
使用UIKit:
UIViewController
子类,例如CustomNavigationController.swift
。import UIKit
class CustomNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
let customViewController = CustomViewController()
self.setViewControllers([customViewController], animated: false)
}
}
UIViewController
,并在其中添加自定义导航栏:import UIKit
class CustomViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "My Custom Navigation"
let backButton = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(backAction))
self.navigationItem.leftBarButtonItem = backButton
// 设置自定义背景颜色
navigationController?.navigationBar.barTintColor = .blue
// 设置自定义标题颜色
navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
}
@objc func backAction() {
navigationController?.popViewController(animated: true)
}
}
AppDelegate.swift
中设置CustomNavigationController
为根视图控制器:import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = CustomNavigationController()
window?.makeKeyAndVisible()
return true
}
}
这样,您就可以在单个文件中自定义NavigationBar了。
领取专属 10元无门槛券
手把手带您无忧上云