SwiftUI-阻止列表将滚动位置重置为项目选择的顶部

时间:2019-06-26 09:30:23

标签: swiftui

因此,一直困扰着SwiftUI,并且一切正常,除了每当选择一个项目时列表会将其滚动位置重置到顶部。我没有解决此问题。代码-

struct FontSettingsView : View {

    @ObjectBinding var settings: FontSettings

    var body: some View {
        NavigationView {
            ContentView(settings: settings)
                .navigationBarTitle(Text("Font"), displayMode: .inline)
        }
    }

    struct ContentView: View {

        @State var settings: FontSettings

        var body: some View {
            VStack {

                HeaderView(settings: $settings)

                FontListView(excludedFontNames: settings.excludedFontNames) { fontName in
                    self.$settings.name.value = fontName
                }
            }
        }

        struct HeaderView: View {

            @Binding var settings: FontSettings

            var body: some View {
                VStack {

                    HStack {
                        VStack (alignment: .leading) {
                            Text("Custom font size:")
                                .font(.body)
                            Text("If disabled, will use system settings")
                                .font(.caption)
                        }
                        Toggle(isOn: $settings.isCustomSize) {
                            Text("")
                        }
                    }

                    Slider(value: $settings.size, from: 10, through: 30, by: 0.1)
                        .disabled($settings.isCustomSize.value == false)

                    Text("Current font: \($settings.name.value)")
                        .customFont(using: self.settings)
                        .padding()
                        .animation(.default)

                }.padding()
            }
        }

        struct FontListView: View {

            struct FontName: Identifiable {
                var id = UUID()
                let value: String
            }

            private let fontNames: [FontName]
            private let tapped: ((String) -> ())?

            init(excludedFontNames: [String] = [], tapped: ((String) -> ())?) {
                self.fontNames = UIFont.familyNames.sorted().filter({ excludedFontNames.contains($0) == false }).map { FontName(value: $0) }
                self.tapped = tapped
            }

            var body: some View {
                List(fontNames) { fontName in
                    Button(action: {
                        self.tapped?(fontName.value)
                    }) {
                        Text(fontName.value).customFont(named: fontName.value)
                    }
                }
            }
        }
    }
}

不幸的是,所有文档和示例似乎都与选择一个项目时导航到新屏幕有关,这不是我的意图。

一些想要运行整个程序的人的附加代码-

class FontSettings: BindableObject {

    private static let defaultSize: CGFloat = 20

    var didChange = PassthroughSubject<Void, Never>()

    var excludedFontNames: [String] = []

    var name: String = "Helvetica" {
        didSet {
            self.didChange.send()
        }
    }
    var size: CGFloat = FontSettings.defaultSize {
        didSet {
            self.didChange.send()
        }
    }
    var isCustomSize: Bool = false {
        didSet {
            if self.isCustomSize == false {
                self.size = FontSettings.defaultSize
            }
            self.didChange.send()
        }
    }
}


extension View {

    func customFont(named fontName: String, style: UIFont.TextStyle = .body) -> Self.Modified<CustomFont> {
        return self.modifier(CustomFont(fontName: fontName, textStyle: style))
    }

    func customFont(named fontName: String, size: CGFloat) -> Self.Modified<CustomFont> {
        return self.modifier(CustomFont(fontName: fontName, size: size))
    }

    func customFont(using settings: FontSettings) -> Self.Modified<CustomFont> {
        if settings.isCustomSize {
            return self.modifier(CustomFont(fontName: settings.name, size: settings.size))
        }
        return self.modifier(CustomFont(fontName: settings.name, textStyle: .body))
    }
}


struct CustomFont: ViewModifier {

    let fontName: String
    let fontSize: CGFloat?
    let textStyle: UIFont.TextStyle?

    init(fontName: String, textStyle: UIFont.TextStyle) {
        self.fontName = fontName
        self.textStyle = textStyle
        self.fontSize = nil
    }

    init(fontName: String, size: CGFloat) {
        self.fontName = fontName
        self.fontSize = size
        self.textStyle = nil
    }

    // trigger view refresh when the ContentSizeCategory changes
    @Environment(\.sizeCategory) var sizeCategory: ContentSizeCategory

    func body(content: Content) -> some View {

        if let fontSize = self.fontSize {
            return content.font(.custom(self.fontName, size: fontSize))
        }

        guard let textStyle = self.textStyle, let size = self.fontSizes[textStyle] else {
            fatalError("Unrecognized textStyle")
        }

        let fontMetrics = UIFontMetrics(forTextStyle: textStyle)
        let fontSize = fontMetrics.scaledValue(for: size)

        return content.font(.custom(self.fontName, size: fontSize))
    }

    // normal font sizes per style, as defined by Apple
    private let fontSizes: [UIFont.TextStyle: CGFloat] = [
        .largeTitle: 34,
        .title1: 28,
        .title2: 22,
        .title3: 20,
        .headline: 17,
        .body: 17,
        .callout: 16,
        .subheadline: 15,
        .footnote: 13,
        .caption1: 12,
        .caption2: 11
    ]
}

2 个答案:

答案 0 :(得分:0)

我确定还有更好的方法,但这是我用于基本选择的方法

基本上存储一组ID,然后将每个单元格的绑定传递给该ID

然后在单元格选择上添加/删除集合。

struct Person: Identifiable {
    var name: String
    var id = UUID().uuidString
}

struct ContentView: View {

    @State private var selectedItems = Set<String>([])
    @State private var items = [
        Person(name: "A"),
        Person(name: "B"),
        Person(name: "C"),
        Person(name: "D"),
        Person(name: "E"),
        Person(name: "F"),
        Person(name: "G"),
        Person(name: "H"),
        Person(name: "I"),
        Person(name: "J"),
        Person(name: "K"),
        Person(name: "L")
    ]

    var body: some View {
        List {
            ForEach(self.items) { item in
                Row(item: item, selectedItems: self.$selectedItems)
            }.listRowInsets(EdgeInsets.appDefault())
        }
    }
}

struct Row: View {

    var item: Person
    @State private var isSelected: Bool = false
    // ref to list of current selected items
    @Binding var selectedItems: Set<String>

    private func isInSelectedList(_ item: Person) -> Bool {
        selectedItems.contains(item.id)
    }

    var body: some View {
        HStack {
            VStack(alignment: .leading) {
                Text(item.name)
                    .font(.headline)
            }

            Spacer()

            Image(systemName: isSelected ? "checkmark.circle.fill" : "circle")
                .font(Font.system(size: 40, weight: .light))
                .foregroundColor(isSelected ? Color(UIColor.systemGreen) : Color.secondary.opacity(0.6))
                .onTapGesture {
                    // use the main view as the view model
                    self.addOrRemoveFromSelectedList(self.item)
                    // tap circle to add - then re check if should show tick or not
                    self.isSelected = self.isInSelectedList(self.item)
                }

        }
        .frame(height: 80)
        .padding([.top, .bottom])
        .onAppear {
            // after scrolling away the selection is set when cell shown again
            self.isSelected = self.isInSelectedList(self.item)
        }
    }

    private func addOrRemoveFromSelectedList(_ item: Person) {
        if selectedItems.contains(item.id) {
            selectedItems.remove(item.id)
        } else {
            selectedItems.insert(item.id)
        }
    }
}

// stops the annoying inseting of cell when selected
extension EdgeInsets {
    static func appDefault() -> EdgeInsets {
        return .init(top: 0, leading: 16, bottom: 0, trailing: 16)
    }
}

答案 1 :(得分:0)

嘿,所以我发现,如果在ScrollView中使用ForEach,则在使用onTap手势识别器时它不会重置滚动位置

ScrollView {
            ForEach(podcast, id: \.id) { item in
                PodcastRow(item: item, audioPlayer: audioPlayer)
                    .padding(.leading)
            }
            .navigationBarTitle(Text("\(podcastTitle)"))
            .onAppear {
                self.loadPodcasts()
            }
        }

希望这就是您要寻找的