1
votes

I need to be able to add a tap gesture recognizer to the navigation bar title. But that doesn't seem supported in SwiftUI? Is there any workaround, have other people managed to do this?

On a related note, is it not possible to show a custom View as the navigation bar title? Right now I can only have a Text view, not an Image for example (or a Text view with a gesture modifier..).

3

3 Answers

0
votes

It isn't very elegant but using one of your navigationBarItems() works.

struct ContentView: View {
    var body: some View {
        NavigationView{
            Text("Hello World!")
                .navigationBarItems(leading:YourView())
        }
    }
}
0
votes

I do like this

struct TestView: View {
 @State static var title = "Some title text"
 @State static var profileImage = "person.crop"
 @State static var action : Int = 0
 ... 
 var body: some View {
    NavigationView {
    ...


    .navigationBarItems(leading: TitleLabel(title: TestView.$title), trailing: ProfileButton(imageName: TestView.$profileImage, action: TestView.$action))
    .navigationBarTitle(Text(""), displayMode: .inline)
   }
}
}

and

struct TitleLabel: View {
@Binding var title: String
var body: some View {
    VStack {
        Text(self.title)
            .font(.title)
            .foregroundColor(Color.blue)
            .fontWeight(.bold)
    }
    .padding(EdgeInsets.init(top: 0, leading: 0, bottom: 0, trailing: 0))
}
}

struct ProfileButton: View {
@Binding var imageName: String
@Binding var action: Int
@State private var showModal = false
var body: some View {
    VStack {
        Button(action: {

        }) {
            Image(systemName: imageName)
                .resizable()
                .imageScale(.large)
                .frame(width: 36, height: 36, alignment: .center)
                .padding(EdgeInsets.init(top: 0, leading: 0, bottom: 5, trailing: -20))
                .foregroundColor(Color.black)

        }
    }
    .padding(.horizontal)
}

func doAction(action: Int) {
    switch action {
    case 0:
        print("open profile")
    default:
        print("Unkown action")
    }
}
}
0
votes

Very late to the party, but here's a very good example I have found, which is working for iOS 14+.

.toolbar {
        ToolbarItem(placement: .principal) {
            VStack {
                Text("Title").font(.headline)
                Text("Subtitle").font(.subheadline)
            }
        }
    }

Credit goes to the author of the blog post, who just saved me some further digging.