英文:
How to customise navigation title in SwftUI
问题
我有一个非常简单的NavigationStack,我想要自定义标题,但似乎找不到正确的修饰符来实现这一目标。
NavigationStack {
    List {
        NavigationLink {
            Text("我的子视图")
        } label: {
            Label("子视图")
        }
    }.navigationTitle("父视图")
}
我想要改变.navigationTitle的字体样式,并且能够添加一个按钮到右侧。当我添加一个.font修饰符到.navigationTitle时,它会添加到列表项而不是标题上。而.navigationTitle似乎只接受一个字符串。
我希望实现如下效果(我的按钮将是一个+而不是一个尖角)。
从我了解的情况来看,似乎无法使用navigationTitle来实现这一目标。但是,如果我不使用它,返回按钮的标题会显示错误(它会显示文本“返回”而不是“父视图”)。
英文:
I have a very simple NavigationStack that I would like to customise the title, but I can't seem to find the right modifiers to achieve this.
NavigationStack {
    List {
        NavigationLink {
            Text("My Child View")
        } label: {
            Label("Child View")
        }
    }.navigationTitle("Parent View")
}
I would like to change how the font looks for the .navigationTitle and be able to add a button to the right. When I add a .font modifier to .navigationTitle it adds it to the list items, not the title. And .navigationTitle only appears to accept a string.
I am looking to achieve the below (my button will be a + rather than a chevron).
From what I can tell, I can't use navigationTitle to achieve this. However, if I don't use that, then the back button has the wrong title (it uses the text Back instead of Parent View).
答案1
得分: 2
你可以使用.toolbar修饰符来实现这两者:
public var body: some View {
    NavigationStack {
        List {
            NavigationLink {
                Text("我的子视图")
            } label: {
                Label("子视图", systemImage: "questionmark")
            }
        }
        .toolbar {
            ToolbarItem(placement: .navigationBarLeading) {
                Text("父视图")
                    .font(.system(size: 22, weight: .bold))
            }
            ToolbarItem(placement: .navigationBarTrailing) {
                Button {
                    
                } label: {
                    Image(systemName: "plus")
                }
            }
        }
    }
}
英文:
You can achieve both using the .toolbar modifier:
    public var body: some View {
        NavigationStack {
            List {
                NavigationLink {
                    Text("My Child View")
                } label: {
                    Label("Child View", systemImage: "questionmark")
                }
            }
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Text("Parent View")
                        .font(.system(size: 22, weight: .bold))
                }
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button {
                        
                    } label: {
                        Image(systemName: "plus")
                    }
                }
            }
        }
    }
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。



评论