SwiftUI: List Refresh scrolls up

为君一笑 提交于 2020-01-25 06:41:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!