英文:
I'm currently customizing the back button in SwiftUI manually screen by screen, how do I make this change global?
问题
我的原始目标是调整返回按钮,使其不包含“返回”文本。但我的当前实现需要将以下代码添加到需要返回按钮的每个屏幕上。如何将存在于多个屏幕上的此代码变成一个更全局的更改?
@Environment(\.presentationMode) var presentationMode
// 任何内容
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
HStack {
Image(systemName: "arrow.left")
.foregroundColor(.black)
.font(.headline)
}
}
}
}
结果:
对于使这个更改变为全局的任何帮助将不胜感激
英文:
My original goal was to adjust the back button so it did not include the "back" text. But my current implementation requires adding the following code to each screen that needs a back button. How can I take this code which is on multiple screens and make it a more global change?
@Environment(\.presentationMode) var presentationMode
// Whatever content
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
HStack {
Image(systemName: "arrow.left")
.foregroundColor(.black)
.font(.headline)
}
}
}
}
The result:
Any help on making this change global will be much appreciated
答案1
得分: 0
感谢 @rapiddevice 指出我可以创建一个自定义修饰符,这将使事情变得容易得多。
import SwiftUI
struct CustomBackButton: ViewModifier {
@Environment(\.presentationMode) var presentationMode
func body(content: Content) -> some View {
content
.navigationBarBackButtonHidden(true)
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
HStack {
Image(systemName: "arrow.left")
.foregroundColor(.black)
.font(.headline)
}
}
}
}
}
}
extension View {
func customBackButton() -> some View {
modifier(CustomBackButton())
}
}
英文:
Thank you to @rapiddevice for pointing out I can make a custom modifier which makes things A LOT easier.
import SwiftUI
struct CustomBackButton: ViewModifier {
@Environment(\.presentationMode) var presentationMode
func body(content: Content) -> some View {
content
.navigationBarBackButtonHidden(true)
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
HStack {
Image(systemName: "arrow.left")
.foregroundColor(.black)
.font(.headline)
}
}
}
}
}
}
extension View {
func customBackButton() -> some View {
modifier(CustomBackButton())
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论