I'm trying to show a dynamic List
with rows containing Toggle
elements. The Toggle
s are laid out correctly initially, but their layout breaks when scrolling them in and out of view (ie 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 Toggle
s to show correctly?
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)
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())
}
}
}
}
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!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.