问题
I am new to SwiftUI.
I have a view declared like this:
struct MyScrollView: View {
@ObservedObject var model:MyModel
var body: some View {
ScrollView {
HStack {
ForEach(model.items!, id: \.self) { title in
Text(title)
}
}
}
Now I want to create a new kind of scrollView, that inherits all this defined for MyScrollView. In fact I would love to create an "instance" of MyScrollView and extend its methods and properties.
The problem is that structs cannot be instanced.
If MyScrollView was a class what I would like is this:
class MySuperScrollView: MyScrollView {
var anotherProperty:Bool
func anotherFunction() -> Bool {
return anotherProperty
}
}
^ this in terms of struct.
回答1:
You cannot inherit struct views, but you can aggregate one into another, like
struct MySuperScrollView: View {
@ObservedObject var model: MyModel
var anotherProperty:Bool
func anotherFunction() -> Bool {
return anotherProperty
}
var body: some View {
// ... other elements around
MyScrollView(model: self.model)
// ... other elements around
}
}
回答2:
Inheritance is not the way to create reusable SwiftUI views that you can extend with extra properties.
Instead of using inheritance, you should use composition, which means that you break up your views into small reusable components and then add these views to the body of your other view to compose a more complex view.
However, without seeing exactly what changes you want to achieve, I cannot give you an exact code example.
来源:https://stackoverflow.com/questions/65671099/swiftui-accessing-a-property-of-a-generic-observed-class