gpt4 book ai didi

ios - 在 SwiftUI 中构建自定义的类似 TabView 的 View

转载 作者:行者123 更新时间:2023-11-28 07:19:52 29 4
gpt4 key购买 nike

我一直在尝试为 macOS 构建一个 toolbar-tabview 组件,它可以与 subview 组成,就像下面的 TabView 一样:

struct ContentView: View {    
var body: some View {
TabView {
Text("First View")
.tabItem {
Image(name: "NSUserAccounts")
Text("First")
}.tag(0)
Text("Second View")
.tabItem {
Image(name: "NSUserAccounts")
Text("Second")
}.tag(1)
}
}
}

目前我有这样的事情:

struct ToolbarTabView<Content>: NSViewControllerRepresentable where Content: View {

let content: () -> Content

init(@ViewBuilder content: @escaping () -> Content) {
self.content = content
}

func makeNSViewController(context: NSViewControllerRepresentableContext<ToolbarTabView>) -> NSTabViewController {
let vc = NSTabViewController()
vc.tabStyle = .toolbar


for item in self.content() as! something? {
let t = NSTabViewItem(viewController: NSHostingController(rootView: item))
t.image = item.image
t.label = item.label
t.identifier = item.identifier
vc.addTabViewItem(t)
}

return vc
}

func updateNSViewController(_ nsViewController: NSTabViewController, context: NSViewControllerRepresentableContext<ToolbarTabView>) {
}

typealias NSViewControllerType = NSTabViewController


}

SwiftUI 可以实现这样的功能吗? TabView 内容如何被转换并用于获取 Image 和 Label 信息?

最佳答案

除了将内容传递给您的 ToolbarTabView 之外,您还可以让它接受一个也包含其他值的数组。尝试这样的事情:

struct ToolbarTabView<Content>: NSViewControllerRepresentable where Content: View {

let tabs: [(imageName: String, label: String, identifier: Int, content: () -> Content)]

init(tabs: [(imageName: String, label: String, identifier: Int, content: () -> Content)]) {
self.tabs = tabs
}

func makeNSViewController(context: NSViewControllerRepresentableContext<ToolbarTabView>) -> NSTabViewController {
let vc = NSTabViewController()
vc.tabStyle = .toolbar


for item in tabs {
let t = NSTabViewItem(viewController: NSHostingController(rootView: item.content()))
//t.image = item.image
t.label = item.label
t.identifier = item.identifier // this causes an "unrecognized selector" error, but maybe I'm passing a bad value for this, I'm not sure what it expects
vc.addTabViewItem(t)
}

return vc
}

func updateNSViewController(_ nsViewController: NSTabViewController, context: NSViewControllerRepresentableContext<ToolbarTabView>) {
}

typealias NSViewControllerType = NSTabViewController


}

struct ToolbarTabView_Previews: PreviewProvider {
static var previews: some View {
ToolbarTabView(tabs: [
(
imageName: "My Image",
label: "tab1",
identifier: 0,
content: {
Text("testing")
}
)
])
}
}

关于ios - 在 SwiftUI 中构建自定义的类似 TabView 的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58513264/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com