gpt4 book ai didi

SwiftUI:可重用跨平台(iOS 和 macOS) View 中的导航栏标题

转载 作者:行者123 更新时间:2023-11-30 10:27:48 25 4
gpt4 key购买 nike

我正在尝试为框架创建可重用的 SwiftUI View,然后可以在 iOS/iPadOS 和 macOS 上使用。

这通常工作得很好;但是,由于 macOS View 没有导航栏,因此当 View 包含在 macOS 目标中时,包含导航栏标题(对于 iOS 很重要)会导致错误:

.navigationBarTitle(Text("页面标题"))

Value of type '...' has no member 'navigationBarTitle'

关于允许为两个平台构建相同 View 的条件编译(或任何其他)方法有什么建议吗?

我最接近的是以下内容。包含额外的 Text View 非常简单,但由于栏标题是修饰符,因此在条件编译中仅包装该部分会产生其他错误:

public struct ExampleView: View {

private let pageTitle = "Page Title"

public var body: some View {

VStack(alignment: .center) {

#if os(macOS)
Text(pageTitle)
.font(.title)
#endif

Spacer()
Text("This is the view content")
Spacer()
}

#if !os(macOS)
.navigationBarTitle(Text(pageTitle))
#endif
}
}

Unexpected platform condition (expected 'os', 'arch', or 'swift')

Function declares an opaque return type, but has no return statements in its body from which to infer an underlying type

最佳答案

我建立了一种方法:将主要内容移动到另一个 View 属性,然后修改它以添加导航栏标题(如果需要),然后将其作为 body 返回。这样分开后,就可以使用条件编译了。

这有点不优雅,但它确实有效。它还可用于设置 macOS 特定的内容,例如 View 的整体框架大小。欢迎提出更好方法的建议!

Swift v5.1

public struct ExampleView: View {

private let pageTitle = "Page Title"

#if !os(macOS)
public var body: some View {
main.navigationBarTitle(Text(pageTitle))
}
#else
public var body: some View {
main.frame(
minWidth: 500,
minHeight: 500
)
}
#endif
public var main: some View {

VStack(alignment: .center) {

#if os(macOS)
Text(pageTitle)
.font(.title)
#endif

Spacer()
Text("This is the view content")
Spacer()
}
}
}

关于SwiftUI:可重用跨平台(iOS 和 macOS) View 中的导航栏标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59787209/

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