我正在开发一个支持多个配置文件的应用程序。我真的很喜欢 Apple 显示 Profile Icon
的方式在 Large Navigation Bar Title
旁边在他们所有的应用程序中。请参阅下面的屏幕截图:
我的问题如下:
SwiftUI
中实现这一点? ?如果是这样,怎么办? SwiftUI
中不可能,我怎样才能实现它,包括UIKit
代码? 谢谢你的帮助。
最佳答案
我通过使用 SwiftUI-Introspect 解决了这个问题, 到“从 SwiftUI 内省(introspection)底层 UIKit 组件”。
下面是一个 View 示例:
struct ContentView: View {
@State private var lastHostingView: UIView!
var body: some View {
NavigationView {
ScrollView {
ForEach(1 ... 50, id: \.self) { index in
Text("Index: \(index)")
}
.frame(maxWidth: .infinity)
}
.navigationTitle("Large title")
.introspectNavigationController { navController in
let bar = navController.navigationBar
let hosting = UIHostingController(rootView: BarContent())
guard let hostingView = hosting.view else { return }
// bar.addSubview(hostingView) // <--- OPTION 1
// bar.subviews.first(where: \.clipsToBounds)?.addSubview(hostingView) // <--- OPTION 2
hostingView.backgroundColor = .clear
lastHostingView?.removeFromSuperview()
lastHostingView = hostingView
hostingView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
hostingView.trailingAnchor.constraint(equalTo: bar.trailingAnchor),
hostingView.bottomAnchor.constraint(equalTo: bar.bottomAnchor, constant: -8)
])
}
}
}
}
酒吧内容和个人资料图片 View :struct BarContent: View {
var body: some View {
Button {
print("Profile tapped")
} label: {
ProfilePicture()
}
}
}
struct ProfilePicture: View {
var body: some View {
Circle()
.fill(
LinearGradient(
gradient: Gradient(colors: [.red, .blue]),
startPoint: .topLeading,
endPoint: .bottomTrailing
)
)
.frame(width: 40, height: 40)
.padding(.horizontal)
}
}
.frame(width: 40, height: 40)
& hostingView.bottomAnchor
constant
将需要根据您的需要进行调整。每个选项的结果(在代码中注释):
选项1
选项 2
滚动时查看棒
滚动时 View 在下方消失
关于ios - 如何在 SwiftUI 中的大型导航栏标题旁边显示配置文件图标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67202400/