有没有人能给我解释一下ScrollView是如何工作的,当我收到一条消息时,我怎么能让它滚动到最后一条消息(项目)?
我试着用一个ScrollViewReader { proxy in }
做它,但是我仍然不能让这个代码工作。
我也试图使它' .onchange(的:){ } '(带有滚动视图阅读器)
struct ContentView: View{
@ObservedObject var viewModel = ViewModel()
@State var text = ""
@State var models = [String]()
var body: some View {
VStack(alignment: .leading) {
ScrollViewReader { proxy in
ScrollView (showsIndicators: false){
ForEach(models, id: \.self){ string in
Text(string)
.font(.headline)
.padding()
.background(Color("Text"))
.cornerRadius(10)
.overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(.blue, style: .init(lineWidth: 1))
)
Divider()
}
.onChange(of: models){
proxy.scrollTo(models.last)
}
}
}
Spacer()
HStack{
TextField("Type here...", text: $text)
.padding(15.0)
.padding(.horizontal)
Button(){
send()
} label: {
Image(systemName: "arrow.up.circle.fill")
.font(.system(size: 40))
.foregroundColor(Color("Button"))
}
.padding(10.0)
}
.overlay(
RoundedRectangle(cornerRadius: 100)
.stroke(Color("Stroke"), lineWidth: 1)
)
}
.onAppear{
viewModel.setup()
}
.padding()
.background(/*@START_MENU_TOKEN@*//*@PLACEHOLDER=View@*/Color("Background")/*@END_MENU_TOKEN@*/)
}
func send() {
guard !text.trimmingCharacters(in: .whitespaces).isEmpty else {
return
}
models.append("Me: \(self.text)")
viewModel.send(text: text) { response in
DispatchQueue.main.async {
self.models.append("Answer: "+response)
self.text = ""
}
}
}
}
..............................
1条答案
按热度按时间6yoyoihd1#
使用不同的重载
代理.scrollTo(模型.最后一个,锚:.顶部)