SwiftUI:列表刷新向上滚动 [英] SwiftUI: List Refresh scrolls up
问题描述
我刚刚发现了一个有趣的行为.如果 List 的 .id(UUID().uuidString) 修饰符被注释,当用户修改了在初始视图中不可见的绑定控件的值时(这意味着该控件可能在靠近列表末尾的某个地方),列表将向上滚动,因为绑定值将刷新视图.但是,如果 .id(UUID().uuidString) 修饰符被注释掉,列表将不会向上滚动,它会保持原样 - 这对我有好处.
我只是好奇这是否是预期的行为.当给列表一个 id 时,有什么可以阻止向上滚动的吗?
<预><代码>导入 SwiftUIstruct ScrollUpProblem: 查看{@EnvironmentObject var qList: MemoryObjectRep//MemoryObjectRep 是一个保存已发布参数的类.var主体:一些视图{导航视图{列表{ForEach(self.qList.QuestionList) { 问题在ScrollUpProblemDetail(问题: self.$qList.QuestionList[self.qList.QuestionList.firstIndex(of: question)!] )}}.id(UUID().uuidString)//<<<<<<<<请注意这里}}}struct ScrollUpProblemDetail:查看{@Binding var 问题:SurveyQuestionvar主体:一些视图{NavigationLink(destination:QuestionCardDetail(question: $question)){HStack(间距:0){文本(任何文本")垫片()切换(isOn:self.$question.BoolValue){文本("")}.id(UUID().uuidString)}}}}id 是视图状态的一部分.如果您更改它,则会重新创建视图.
I just discovered a funny behavior. if .id(UUID().uuidString) modifier of the List is commented, when a user modifies the value of a bound control which is not visible at the initial view (which means the control may be at somewhere towards the end of the list), the list will scroll up as the bound value will refresh the view. However, if .id(UUID().uuidString) the modifier is commented out, the list won't scroll up, it will stay as where it is - which is good for me.
I am just curious if this is the expected behavior. Is there anything that will prevent the scroll up when an id is given to the List?
import SwiftUI
struct ScrollUpProblem: View {
@EnvironmentObject var qList: MemoryObjectRep // MemoryObjectRep is a class keeping published parameters.
var body: some View {
NavigationView{
List{
ForEach(self.qList.QuestionList) { question in
ScrollUpProblemDetail(question: self.$qList.QuestionList[self.qList.QuestionList.firstIndex(of: question)!] )
}
}
.id(UUID().uuidString) // <<<<<<<< ATTENTION HERE
}
}
}
struct ScrollUpProblemDetail: View {
@Binding var question: SurveyQuestion
var body: some View {
NavigationLink(destination:QuestionCardDetail(question: $question)){
HStack(spacing: 0){
Text("AnyText")
Spacer()
Toggle(isOn: self.$question.BoolValue)
{
Text("")
}.id(UUID().uuidString)
}
}
}
}
id is part of the state of the view. if you change it, the view is recreated.
这篇关于SwiftUI:列表刷新向上滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!