問題描述
XCode 版本 13.0 測試版 (13A5155e)&針對 iOS 14 或 15
XCode Version 13.0 beta (13A5155e) & Targeting iOS 14 or 15
我的目標是在 SwiftUI 中創建一個聊天視圖.這需要創建一個具有不同高度內容的 ScrollView.
My goal is to create a chat view in SwiftUI. This requires creating a ScrollView with content of varying heights .
經過大量調試,我確定如果您在 ScrollView 中有沒有固定高度的視圖,當您滾動到視圖頂部時它會卡頓.
After extensive debugging, I've determined that if you have views within the ScrollView that do not have a fixed height, it will stutter when you scroll to the top of the view.
––––
項目: 下載此項目并親自嘗試
struct Message: Identifiable {
let id = UUID()
var text: String
}
struct ContentView: View {
@State var items: [Message] = MockData.randomMessages(count: 100)
var body: some View {
VStack {
Button("Shuffle items") {
items = MockData.randomMessages(count: 100)
}
ScrollView {
LazyVStack(spacing: 10) {
ForEach(items) { item in
Text(item.text)
.background(colors.randomElement()!)
}
}
}
}
}
}
我現在的結論是 LazyVStack
僅適用于具有固定高度的子視圖.僅此問題就導致 SwiftUI 無法投入生產.
My conclusion right now is that LazyVStack
only works with child views that have fixed height. This issue alone prevents SwiftUI from being production ready.
還有其他人解決過這個問題嗎?
Has anyone else tackled this?
蘋果公司的回應(2021 年 7 月 27 日):
"在您的 Mac 目標上,這一切正常,但我發現 iOS 上存在滾動問題.這個問題絕對是 iOS 上 SwiftUI 的一個 bug.我建議不要重寫你的應用程序,而是為你的 UIScrollView 使用 UIViewRepresentable (或者實際上 UITable/UICollection 視圖在這里最有意義).如果您使用可重用的視圖,例如表格或集合,這些問題幾乎肯定會消失.您不需要重寫您的應用,但如果此問題阻止發布,您應該添加 UIViewRepresentable."
"On your Mac target this all works but I see there are scrolling issues on iOS. This issue is definitely a bug with SwiftUI on iOS. I recommend that rather than rewrite your app you use a UIViewRepresentable for your UIScrollView (or actually UITable / UICollection View would make the most sense here). If you use a re-usable view such as a table or collection these issues will almost certainly go away. You shouldn't need to rewrite your app but you should add a UIViewRepresentable if this issue is preventing a release."
推薦答案
在 macos 12.beta、xcode 13.beta、target ios 15 和 macCatalyst 上運行沒有任何問題.在 ios15 設備和 macos 12 上測試.我也嘗試使用 10000,效果很好.也許您的問題發生在較舊的 ios 和 macos 上.您可能對 Swift UI 被高頻 @StateObject 更新淹沒感興趣? 代碼在 ios14 而不是 ios15 上掙扎的地方.
works without any problems on macos 12.beta, xcode 13.beta, target ios 15 and macCatalyst. Tested on ios15 devices and macos 12. I also tried using 10000, and that works well. Maybe your issue happens on older ios and macos. You maybe interested in Swift UI overwhelmed by high-frequency @StateObject updates? where code struggles on ios14 but not ios15.
您可以嘗試其他方法,看看是否可以提高性能,例如:
You could try other ways to see if you can improve the performance, such as:
ForEach(items.indices, id: .self) { index in
Text(items[index]).background(colors.randomElement()!)
}
或
ForEach(Array(items.enumerated()), id: .0) { index, item in
Text(item).background(colors.randomElement()!)
}
這篇關于ScrollView 內的 LazyVStack 中具有可變高度的內容導致口吃/跳躍的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!