[英]Problem binding a subclass to parent class in SwiftUI View
I've been experimenting on trying to binding subclass to a SwiftUI view that takes it parent class as a parameter.我一直在尝试尝试将子类绑定到 SwiftUI 视图,该视图将其父 class 作为参数。
These are my classes:这些是我的课:
class Animal {
func sound() -> String {
return ""
}
}
class Cat : Animal {
override func sound() -> String {
return "Meow"
}
func purr() {
print("purring")
}
}
class Dog : Animal {
override func sound() -> String {
return "Woof"
}
func fetch() {
print("fetching")
}
}
Here are the views I have set up.这是我设置的视图。
struct ContentView: View {
@State var creature:Cat = Cat()
var body: some View {
AnimalView(creature: $creature)
}
}
struct AnimalView: View {
@Binding var creature:Animal
var body: some View {
Text(creature.sound())
.padding()
}
}
This results in the compile error:这会导致编译错误:
Cannot convert value of type 'Binding<Cat>' to expected argument type 'Binding<Animal>'
What the proper way to do bind to a view the takes a parent class?绑定到需要父 class 的视图的正确方法是什么?
Searching around I think the structure I would want is to make the view itself generic.环顾四周,我认为我想要的结构是使视图本身具有通用性。
struct ContentView: View {
@State var creature:Cat = Cat()
@State var creature2:Dog = Dog()
var body: some View {
VStack {
AnimalView(creature: $creature)
AnimalView(creature: $creature2)
}
}
}
struct AnimalView<T:Animal> : View {
@Binding var creature:T
@State var sound:String = "No Sound"
var body: some View {
Text(creature.name)
.padding()
.onAppear {
self.sound = self.creature.sound()
}
}
}
This will allow me to bind to types that inherit from Animal and let me use one view rather that having to create a separate Cat and Dog view.这将允许我绑定到从 Animal 继承的类型,并让我使用一个视图,而不必创建单独的 Cat 和 Dog 视图。
Also just in case for better form, here is a same thing with protocol and classes.同样为了更好的形式,这里的协议和类也是一样的。
protocol Animal {
var name:String {
get
}
func sound() -> String
}
struct Cat : Animal {
var name:String {
get {
return "Cat"
}
}
func sound() -> String {
return "Meow"
}
func purr() {
print("purring")
}
}
struct Dog : Animal {
var name:String {
get {
return "Dog"
}
}
func sound() -> String {
return "Woof"
}
func fetch() {
print("fetching")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.