英文:
SwiftUI How can we add conditions to modifiers
问题
我想在 macOS 版本为 11 且为新版本时添加 .controlSize 修饰符,但我遇到了问题。我该如何解决这个问题?
Button(action: {
viewModel.getRoomId()
}, label: {
Text("获取 Pin")
.frame(maxWidth: .infinity)
.padding(.all)
.frame(height: 44)
.contentShape(Rectangle()) // 使整个按钮可点击
})
if #available(macOS 11, *) {
.controlSize(.large)
}
英文:
I would like to add the .controlSize modifier when the macOS version is 11 and new but I am having issues. How can I fix this issue
Button(action: {
viewModel.getRoomId()
}, label: {
Text("Get Pin")
.frame(maxWidth: .infinity)
.padding(.all)
.frame(height: 44)
.contentShape(Rectangle()) // Make full button tappable
})
if #available(macOS 11, *) {
.controlSize(.large)
}
答案1
得分: 1
创建一个包装器,将其作为 `View` 的扩展:
```swift
extension View {
func controlSizeIfAvailable(_ controlSize: ControlSize) -> some View {
if #available(macOS 11, *) {
return self.controlSize(controlSize)
}
else {
return self
}
}
}
并像这样使用它:
Button(action: {
viewModel.getRoomId()
}, label: {
Text("获取 Pin")
.frame(maxWidth: .infinity)
.padding(.all)
.frame(height: 44)
.contentShape(Rectangle()) // 使整个按钮可点击
})
.controlSizeIfAvailable(.large)
<details>
<summary>英文:</summary>
Create a wrapper for that modifier as a `View` extension:
extension View {
func controlSizeIfAvailable(_ controlSize: ControlSize) -> some View {
if #available(macOS 11, *) {
return self.controlSize(controlSize)
}
else {
return self
}
}
}
and use it like this:
Button(action: {
viewModel.getRoomId()
}, label: {
Text("Get Pin")
.frame(maxWidth: .infinity)
.padding(.all)
.frame(height: 44)
.contentShape(Rectangle()) // Make full button tappable
})
.controlSizeIfAvailable(.large)
</details>
# 答案2
**得分**: -1
`controlSize` 修饰符本身在 `macOS 11` 之前可用,只是 `large` 大小不可用。
您可以定义类似以下的内容:
```swift
@ViewBuilder
func largeControlSizeCompat() -> some View {
if #available(macOS 11.0, *) {
self.controlSize(.large)
} else {
self.controlSize(.regular)
}
}
然后使用它:
Button("测试") { /* */ }
.largeControlSizeCompat()
英文:
The controlSize
modifier itself is available before macOS 11
, just not the large
size.
You can define something like this:
@ViewBuilder
func largeControlSizeCompat() -> some View {
if #available(macOS 11.0, *) {
self.controlSize(.large)
} else {
self.controlSize(.regular)
}
}
And use it:
Button("Test") { /* */ }
.largeControlSizeCompat()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论