uikit - 如何在 SwiftUI 视图中包装 UIBarButtonItem?
问题描述
我正在尝试为NavigationBar
我可以放置我喜欢的任何文本的位置制作一个自定义的后退按钮。我的主要用例是我的一些视图没有标题,当我从中单击新视图时,导航栏中新视图的后退按钮没有文本,只有一个箭头。它使用户很难点击它。我希望设置一个自定义后退按钮,其中包含文本“Back”,但也有后退按钮图标,并且与 SwiftUI 的动画机制完美配合。
这是我目前尝试将 UIKit 元素包装在 View 中,以便我可以将它与 SwiftUI 一起使用:
struct CustomBackButton: UIViewControllerRepresentable {
typealias UIViewControllerType = ViewController
@Binding var title: String
func makeUIView(context: Context) -> UIBarButtonItem {
return UIBarButtonItem()
}
func updateUIView(_ uiView: UIBarButtonItem, context: Context) {
uiView.title = title
}
}
它显然不起作用,我目前不确定如何使其真正起作用。
我的理想方案是CustomBackButton
这样我可以在 SwiftUI 中像这样使用它:
var body: some View {
NavigationView {
Text("Page with no title")
.navigationBarItems(leading: CustomBackButton(title: "Back"))
.navigationBarTitle("", displayMode: .large)
}
}
我需要做什么才能正确包装CustomBackButton
到 SwiftUI 中View
?
解决方案
如果您只是想拥有自定义文本,则无需为 UIKit 操心。以下是在 SwiftUI 中制作自定义后退按钮的方法:
struct ViewWithCustomBackButton: View {
@Environment(\.presentationMode) var presentationMode
var body: some View {
HStack {
...
}
.navigationBarTitle(Text("Your View"), displayMode: .inline)
// Hide the system back button
.navigationBarBackButtonHidden(true)
// Add your custom back button here
.navigationBarItems(leading:
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
HStack {
Image(systemName: "arrow.left.circle")
Text("Go Back")
}
})
}
}
您还可以在此处查看答案以获取更多信息:SwiftUI 中 NavigationView 导航栏的自定义后退按钮
推荐阅读
- amazon-web-services - 如何在 AWS Glue 中使用 Spark 包?
- html - chrome无法加载spotfire链接
- awk - 更快的字符串替换算法/语言
- angular - Angular:如何在不通过 HTML 的情况下将数据从组件传递到另一个组件?
- typescript - 如何在ts中声明函数之间的依赖关系?
- javascript - 如何在单击按钮时翻转图像并在单击另一个按钮时停止翻转
- python - 无效的 API 密钥/应用程序对–Clarifai
- json - Clojure API 中正确的 JSON 转义
- reactjs - 通过打字稿,如何在接口中声明特定 ReactElement 类型的成员
- mysql - 如何检查mysql中的事件执行持续时间?