向SwiftUI navigationBarTitle添加轻击手势吗?

时间:2020-01-28 18:21:52

标签: swiftui

我需要能够向导航栏标题添加轻击手势识别器。但这似乎在SwiftUI中不支持?有什么解决方法,其他人可以做到吗?

在相关说明中,是否可以将自定义视图显示为导航栏标题?现在,我只能拥有一个“文本”视图,而不是一个图像(或带有手势修改器的“文本”视图。)。

3 个答案:

答案 0 :(得分:0)

它不是很优雅,但是使用您的navigationBarItems()之一有效。

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

答案 1 :(得分:0)

我喜欢

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)
   }
}
}

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")
    }
}
}

答案 2 :(得分:0)

聚会很晚了,但我找到了一个 very good example,它适用于 iOS 14+。

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

感谢博文的作者,他为我节省了一些进一步的挖掘工作。