作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
给出以下示例:
class ProfileTab: Identifiable {
let id = UUID()
let name: String
init(name: String) {
self.name = name
}
}
class ProfileQuoteTab: ProfileTab {
let answer: String
let prompt: String
init(name: String, answer: String, prompt: String) {
self.answer = answer
self.prompt = prompt
super.init(name: name)
}
}
class ProfileImageTab: ProfileTab {
let image: Image
init(name: String, image: Image) {
self.image = image
super.init(name: name)
}
}
struct ContentView: View {
let tabs: [ProfileTab] = [
ProfileQuoteTab(name: "This is a quote tab", answer: "This is an answer", prompt: "This is a prompt"),
ProfileImageTab(name: "This is an image tab", image: Image(systemName: "faceid"))
]
var body: some View {
List(self.tabs) { tab in
VStack {
if tab is ProfileQuoteTab {
Text((tab as! ProfileQuoteTab).answer)
}
if tab is ProfileImageTab {
(tab as! ProfileImageTab).image
}
}
}
}
}
ProfileTab
中不同类的属性?大批?
Closure containing control flow statement cannot be used with function builder 'ViewBuilder'
if let profileImage = tab as? ProfileImage {
...
}
(tab as! ProfileImageTab).image
最佳答案
在所描述的用例中,多态性将如下所示(或在某些变体中):
class ProfileTab: Identifiable {
let id = UUID()
let name: String
init(name: String) {
self.name = name
}
func view() -> AnyView {
AnyView(EmptyView())
}
}
class ProfileQuoteTab: ProfileTab {
let answer: String
let prompt: String
init(name: String, answer: String, prompt: String) {
self.answer = answer
self.prompt = prompt
super.init(name: name)
}
override func view() -> AnyView {
AnyView(Text(self.answer))
}
}
class ProfileImageTab: ProfileTab {
let image: Image
init(name: String, image: Image) {
self.image = image
super.init(name: name)
}
override func view() -> AnyView {
AnyView(self.image)
}
}
struct ContentView: View {
let tabs: [ProfileTab] = [
ProfileQuoteTab(name: "This is a quote tab", answer: "This is an answer", prompt: "This is a prompt"),
ProfileImageTab(name: "This is an image tab", image: Image(systemName: "faceid"))
]
var body: some View {
List(self.tabs) { tab in
VStack {
tab.view()
}
}
}
}
关于swift - 多态性和 SwiftUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59607316/
我来自 Asp.Net 世界,试图理解 Angular State 的含义。 什么是 Angular 状态?它类似于Asp.Net中的ascx组件吗?是子页面吗?它类似于工作流程状态吗? 我听到很多人
我一直在寻找 3 态拨动开关,但运气不佳。 基本上我需要一个具有以下状态的开关: |开 |不适用 |关 | slider 默认从中间开始,一旦用户向左或向右滑动,就无法回到N/A(未回答)状态。 有人
我是一名优秀的程序员,十分优秀!