SwiftUI - List - UIViewRepresantable won't be

2020-03-28 01:58发布

In my list, my UIViewRepresentable won't be updated if it is the only item in list. If I add e.g. a Text to it, it works. To see the effect, scroll down and up again. What am i doing wrong?

Hers is my code:

struct Test : UIViewRepresentable {

    var text : String

    func makeUIView(context: UIViewRepresentableContext<Test>) -> UILabel {
        UILabel()
    }

    func updateUIView(_ uiView: UILabel, context: UIViewRepresentableContext<Test>) {
        uiView.text = text
    }

    typealias UIViewType = UILabel
}

class Data : ObservableObject {

    @Published var names = UIFont.familyNames
}

struct ContentView : View {

    @EnvironmentObject var data : Data

    var body: some View {
        VStack {
            List(data.names, id: \.self) { name in
                Test(text: name)
        //        Text(name)  // as soon as you comment this out, it works
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

标签: swiftui
1条回答
一夜七次
2楼-- · 2020-03-28 02:59

For now I know variant/workaround that works (tested on all available Xcode 11.x)

var body: some View {
    VStack {
        List(data.names, id: \.self) { name in
            Test(text: name).id(name) //           << here !!
        }
    }
}

Note: it might be performance drop on very big lists, but in most usual cases it is not remarkable.

PS: By the way, about class Data - don't name your classes with same names as system one, there might be confuses and unexpectable issues.

查看更多
登录 后发表回答