SwiftUI - Accessing a property of a generic observed class

╄→гoц情女王★ 提交于 2021-01-24 10:34:32

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!