问题
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)
}
}
}
}
回答1:
id is part of the state of the view. if you change it, the view is recreated.
来源:https://stackoverflow.com/questions/59867013/swiftui-list-refresh-scrolls-up