在SwiftUI的导航栏中设置图像和标题

时间:2020-07-06 12:30:43

标签: ios navigation swiftui uinavigationbar swiftui-environment

AppStore app has an icon with an image on the right side of the NabBar with Large Title: 如果有人知道如何实现它或有关如何实现的想法,我将非常感谢。

2 个答案:

答案 0 :(得分:0)

UIKIT完成。

这是代码的样子

let viewA = UIView()
let viewB = UIView()

private func setupNavigationBarAppearance() {

        viewA.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didViewA)))
        viewB.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didViewB)))
        
        let leftBarButtonItem = UIBarButtonItem(customView: viewA)
        let rightBarButtonItem = UIBarButtonItem(customView: viewB)
        
        navigationItem.leftBarButtonItem = leftBarButtonItem
        navigationItem.rightBarButtonItem = rightBarButtonItem
        navigationItem.title = "Hello World"
        
    }

@objc private func didViewA() {
        print("Hello")
    }
    
    @objc private func didViewB() {
        print("World")
    }

我在这里使用UIView是因为ImageView是UIView的子类,因此您可以将其与ImageView关联。如果不需要,也可以删除左或右barButtonItem。

答案 1 :(得分:-1)

这基本上可以满足您的需求。在声明displayMode: .automatic时使用navigationBarTitle意味着它将一直显示为largeTitle,直到滚动为止,NavBar会转到displayMode: .inline。 例如,我仅使用SF Symbols图像,但是您可以用相同的方式更换Cap的防护罩。如果需要互动,请将其包装在按钮中。

struct ContentView: View {
    var body: some View {
        NavigationView {
            List(0...1000, id: \.self) { _ in
                Text("Sample")
            }
            .navigationBarTitle("Large Title", displayMode: .automatic)
            .navigationBarItems(trailing: Image(systemName: "shield"))
        }
    }
}