SwiftUI:动态`List` 中的`Toggle`s 会在重用时破坏其布局吗? [英] SwiftUI: `Toggle`s within dynamic `List` breaking their layout upon reuse?
问题描述
我正在尝试显示包含 Toggle
元素的行的动态 List
.Toggle
最初的布局是正确的,但是在滚动它们进出视图时(即在单元格重用时),它们的布局会中断.
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 (i. e. upon cell reuse).
最小示例代码:
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")
}
}
}
显示问题的屏幕录制:
(这是在模拟器上使用 iOS 13.2.2 (17B102).)
(This is using iOS 13.2.2 (17B102) on the Simulator.)
我做错了什么,还是这是一个错误?如何让 Toggle
正确显示?
Am I doing something wrong, or is this a bug? How do I get the Toggle
s to show correctly?
推荐答案
这是 iOS 13.2+ 中的一个错误/回归
工作 - iOS 13.1 (17A844)/Xcode 11.1 (11A1027)
损坏 - iOS 13.2.2 (17B102)/Xcode 11.2.1 (11B500)
损坏 - iOS 13.3 beta (17C5032d)/Xcode 11.3 beta (11C24b)
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)
解决方法
此错误似乎只影响采用 data
参数的 List
初始值设定项.此代码在功能上是等效的,但不受该错误的影响.
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())
}
}
}
}
这篇关于SwiftUI:动态`List` 中的`Toggle`s 会在重用时破坏其布局吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!