SwiftUI: `Toggle`s within dynamic `List` breaking their layout upon reuse?

家住魔仙堡 提交于 2019-12-08 04:46:23

问题


I'm trying to show a dynamic List with rows containing Toggle elements. The Toggles are laid out correctly initially, but their layout breaks when scrolling them in and out of view (i. e. upon cell reuse).

Minimal example code:

import SwiftUI

struct SwitchList: View {
    var body: some View {
        List(0..<20) { _ in
            SwitchRow(value: Bool.random())
        }
    }
}

struct SwitchRow: View {
    @State var value: Bool

    var body: some View {
        Toggle(isOn: $value) {
            Text("A switch row")
        }
    }
}

Screen recording demonstrating the issue:

(This is using iOS 13.2.2 (17B102) on the Simulator.)

Am I doing something wrong, or is this a bug? How do I get the Toggles to show correctly?


回答1:


This is a bug/regression in iOS 13.2+

Working - iOS 13.1 (17A844) / Xcode 11.1 (11A1027)
Broken - iOS 13.2.2 (17B102) / Xcode 11.2.1 (11B500)
Broken - iOS 13.3 beta (17C5032d) / Xcode 11.3 beta (11C24b)

Submit feedback to Apple

Workaround

This bug only appears to affect the List initializers which take a data parameter. This code is functionally equivalent, but is not affected by the bug.

struct SwitchList: View {
    var body: some View {
        List {
            ForEach(0..<20) { _ in
                SwitchRow(value: Bool.random())
            }
        }
    }
}



回答2:


I was able to reproduce the problem, but could not find out why this happens. When I use a ScrollView() with a Devider() I don't have the Problem anymore. Here is the code:

struct SwitchList: View {
    var body: some View {
        ScrollView {
            ForEach(1...50, id: \.self) { item in
                VStack {
                    SwitchRow(value: Bool.random())
                    Divider()
                }
            }
        }
    }
}

struct SwitchRow: View {
    @State var value: Bool

    var body: some View {
        Toggle(isOn: $value) {
            Text("A switch row")
        }
    }
}

I hope this helps!



来源:https://stackoverflow.com/questions/58916945/swiftui-toggles-within-dynamic-list-breaking-their-layout-upon-reuse

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