gpt4 book ai didi

swiftui - ScrollView 中的 ScrollTo 无法按预期工作

转载 作者:行者123 更新时间:2023-12-05 02:39:01 25 4
gpt4 key购买 nike

基本 ScrollView 。当为 scrollView.scrollTo(value,anchor:.bottom) 使用 value 时,它​​会滚动。当替换为它的值 "99"时,它不会。不确定这是否有意。如果不是,想知道如何使用 id 的值而不是从元素的位置检索它。

struct Testchat: View {
@State private var listMessages: [MessageTest] = []
@State private var scrolled = false

var body: some View {
ScrollViewReader { scrollView in
ScrollView {
VStack(spacing: 0) {
ForEach(listMessages, id: \.id) { messageInList in
Text(messageInList.id)
.onAppear {
if !scrolled {
let value = listMessages[99].id
scrollView.scrollTo("99",anchor: .bottom)
scrolled = true
}
}
}
}
}
}
.onAppear {
for i in 0 ..< 100 {
let messagetest:MessageTest = .init()
messagetest.id = i.description
messagetest.message = i.description
listMessages.append(messagetest)
}
}
}
}
public class MessageTest: NSObject, Codable, ObservableObject {
var message: String!
var id: String!

public override init() {
message = "VOID"
id = "VOID"
}
}

最佳答案

在你的ForEach ,您正在通过 \.id 识别每一行关键路径。 id属性(property) MessageTest是可选的,类型为 String! (但实际上 String? 表示 Optional<String> )。

因此,您需要将要滚动到的行作为 String? 传入输入,而不仅仅是 String .

通过添加强制转换将行更改为以下内容:

scrollView.scrollTo("99" as String?, anchor: .bottom)

链接 here如何回答 String?String!都是Optional<String> ,但是 !版本只是隐式强制解包。

关于swiftui - ScrollView 中的 ScrollTo 无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69287321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com