首页 > 解决方案 > SwiftUI:列表中的分页问题

问题描述

我正在尝试使用 List 在 SwiftUI 中创建分页,但是在滚动时它的行为不正确并且它的大小发生了变化。

这是我正在使用的代码。

class ViewModel: ObservableObject {
    @Published var feeds:[String] = []

    init() {
        for i in 0..<10{
            feeds.append("Page \(i)")
        }
    }

    func appentNewData() -> Void{
        for i in self.feeds.count..<(self.feeds.count + 10){
            feeds.append("New Page \(i)")
        }
    }
}

struct ContentView: View {

@ObservedObject var viewModel = ViewModel()

@State var isExpanded:Bool = false

var body: some View {
    VStack(spacing:0){
        Button(action: {
            withAnimation {
                self.isExpanded.toggle()
            }
        }) {
            Text("Search Bar ( Tap to expand )")
                .font(.title)
                .foregroundColor(Color.black)
            
        }
        .frame(height: self.isExpanded ? 200 : 100)
        .frame(maxWidth:.infinity)
        .background(Color.red)
        
        GeometryReader { (proxy) in
            List{
                ForEach(self.viewModel.feeds, id:\.self) { feed in
                    FeedView(text: feed, size: proxy.size)
                        .listRowInsets(.init(top: 0, leading: 0, bottom: 0, trailing: 0))
                        .frame(width:proxy.size.width, height: proxy.size.height)
                        .border(Color.green ,width: 5.0)
                        .onAppear {
                            guard let lastItem = self.viewModel.feeds.last else{
                                return
                            }
                            if lastItem == feed{
                                self.viewModel.appentNewData()
                            }
                        }
                }
            }
            .frame(width:proxy.size.width, height: proxy.size.height)
            .background(Color.purple)
            .onAppear {
                UITableViewCell.appearance().selectionStyle = .none
                UITableView.appearance().separatorStyle = .none
                UITableView.appearance().isPagingEnabled = true
                UITableView.appearance().separatorStyle = .none
                UITableView.appearance().showsVerticalScrollIndicator = false
            }.onDisappear {
                UITableView.appearance().isPagingEnabled = false
                UITableView.appearance().showsVerticalScrollIndicator = true
            }
        }
    }.clipped()
}
}

struct FeedView:View {
@State var text:String
var size:CGSize
var body: some View{
    VStack(spacing: 20.0){
        Text(text)
            .font(.largeTitle)
        HStack{
            Text("Width : \(size.width)")
                .font(.headline)
            Text("Height : \(size.height)")
                .font(.headline)
        }
    }
    .frame(maxWidth:.infinity,maxHeight: .infinity,alignment: .center) 
}
}

它的行为是这样的。

在此处输入图像描述

不知道为什么它不平均划分行,因为每行具有相同的宽度和高度。

如果有人想尝试,这是一个快速项目。

标签: iosswiftswiftui-listswiftui

解决方案


推荐阅读