首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Swift4分页

Swift4分页
EN

Stack Overflow用户
提问于 2018-03-27 12:04:36
回答 1查看 2.5K关注 0票数 1

我是开发ios应用程序的新手。还是不知道多少。我可以成功地显示文章只从第一页,但未能显示其他文章从其他网页时,我滚动向上看更多。如果有人知道如何从我的收藏视图分页,我真的需要帮助。下面是我使用的api的图片。

下面是我从api获取数据的代码-- (Artikel.swift)

代码语言:javascript
复制
import Foundation
import Alamofire
import SwiftyJSON
import os.log

struct Artikel: ServiceCompletionHandler {
    static func getCategories (completionHandler: @escaping ArrayCompletionHandler) {
        let headers: HTTPHeaders = [
            "Accept": "application/json"
        ]
        let parameters: Parameters = [
            "secret_key": Config.api_key
        ]
        Alamofire.request("\(Config.server_address)/article-categories", method: .post, parameters: parameters, headers: headers)
            .responseJSON { (response) -> Void in
                switch response.result {
                case .success:
                    let json = JSON(response.result.value!)
                    if json["data"].exists() {
                        if let data = json["data"]["data"].array {
                            completionHandler(data, nil)
                        } else {
                            completionHandler([], nil)
                        }
                    } else {
                        completionHandler([], nil)
                    }
                case .failure(let error):
                    print(error)
                    completionHandler([], "Network error has occured.")
                }
        }
    }
    static func getArticles(_ category_id: Int, completionHandler: @escaping ArrayCompletionHandler) {
        let headers: HTTPHeaders = [
            "Accept": "application/json",
            "secret-key": Config.api_key]

        let value: Int = category_id
        let newcategory = String(describing: value)

//        var nextpages = NewsSectionViewController.url

        let new_api = Config.server_addforarticle + newcategory

        Alamofire.request(new_api, method: .get, headers: headers)
            .responseJSON { (response) -> Void in
                switch response.result {
                case .success:
                    let json = JSON(response.result.value!)
//                    dump(json, name: "testing")
                    if let articles = json["articles"]["data"].array {
                        completionHandler(articles, nil)

                    }else{
                        completionHandler([], nil)
                    }
                case .failure(let error):
                    print(error)
                    completionHandler([], "Network error has occured.")
                }
        }
    }
    }

在这里我展示我的文章。但是是的,我不能只按4到5篇文章分页。我只是不知道如何做我在我的android版本所做的。

NewsSectionViewController.swift

代码语言:javascript
复制
import UIKit
import SwiftyJSON
import AlamofireImage

protocol NewsSectionViewControllerDelegate {
    func updateArrowPosition()
}

class NewsSectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    // MARK: - Variables
    var itemIndex: Int = 0
    var category:JSON!
    var stories:[JSON] = []
    var delegate: NewsSectionViewControllerDelegate?

    // MARK: - Views
    @IBOutlet var titleLabel: UILabel!
    @IBOutlet var collectionView: UICollectionView!
    @IBOutlet var loadingIndicator: UIActivityIndicatorView!

    // MARK: - Constraint
    @IBOutlet var titleTopConstraint: NSLayoutConstraint!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.titleLabel.text = category["name"].stringValue.uppercased()

        self.collectionView.contentInset = UIEdgeInsetsMake(0, 0, 114, 0)
        if #available(iOS 11.0, *) {
            if ((UIApplication.shared.keyWindow?.safeAreaInsets.top)! > CGFloat(0.0)) {
                self.collectionView.contentInset = UIEdgeInsetsMake(0, 0, 173, 0)
                self.collectionView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 173, 0)
            }
        }

        self.loadingIndicator.startAnimating()
        Artikel.getArticles(category["id"].intValue) {
            (articles, error) in
            self.loadingIndicator.stopAnimating()
            if error == nil {
                self.stories = articles
                self.collectionView.reloadData()
            }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Collection View
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.stories.count - 1
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        var cell: NewsItemCollectionViewCell?

        let item = stories[indexPath.row + 1]

        if indexPath.row == 0 {
            cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BigCell", for: indexPath) as? NewsItemCollectionViewCell
        } else {
            cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SmallCell", for: indexPath) as? NewsItemCollectionViewCell
        }

        cell!.titleLabel.text = item["title"].stringValue

        if let thumbUrlString = item["banner_url_large"].string {
            if let thumbUrl = URL(string: thumbUrlString) {
                cell?.coverImageView.af_setImage(withURL: thumbUrl)
            }
        }

        let wpDateFormatter = DateFormatter()
        wpDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

        let dayDateFormatter = DateFormatter()
        dayDateFormatter.dateStyle = .medium
        dayDateFormatter.doesRelativeDateFormatting = true

        let date = wpDateFormatter.date(from: item["date_publish_web"].stringValue)!
        cell!.timestampLabel.text = dayDateFormatter.string(from: date)

        return cell!

    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let story = self.stories[indexPath.row + 1]

        let newsContents = self.storyboard?.instantiateViewController(withIdentifier: "NewsContent") as! NewsContentViewController
        newsContents.story = story
        newsContents.title = self.category["name"].string
        self.navigationController?.pushViewController(newsContents, animated: true)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if indexPath.row == 0 {
            let width = UIScreen.main.bounds.width - 30
            return CGSize(width: width, height: 385 - 20)
        } else {
            let width = (UIScreen.main.bounds.width - 45) / 2
            return CGSize(width: width, height: 210)
        }

    }

    // MARK: - ScrollView
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView == self.collectionView {
            self.titleTopConstraint.constant = 30 - scrollView.contentOffset.y
        }
        if let delegate = self.delegate {
            delegate.updateArrowPosition()
        }
    }


    /*
     // MARK: - Navigation

     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */

}

我真的很感激并预先感谢你的任何帮助:)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-03-27 12:40:40

在NewsSectionViewController中:

1)增加全局变量:

a) var nextPageUrl: String?

( b) let numberOfPagination = 5 (5它是一个网址页中的多个项目);

( c)添加变量hasMoreItems

代码语言:javascript
复制
var hasMoreItems: Bool {
    get {
        guard let count = nextPageUrl?.count, count > 0 else {
            return false
        }
        return true
    }
}

( d)添加变量numberOfItems

代码语言:javascript
复制
var numberOfItems: Int {
    get {
        return secrets.count
    }
}

2)将该行self.stories = articles更改为self.stories += articles

3)添加分页功能:

代码语言:javascript
复制
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

    if (indexPath.item + 1 == numberOfItems) && ((indexPath.item + 1) % numberOfPagination == 0) {

        if self.presenter.hasMoreItems {
            self.loadData()
        }
    }
}

( f)加入func loadData()

代码语言:javascript
复制
func loadData() {
    Artikel.getArticles(category["id"].intValue, nextPageUrl: nextPageUrl) {
        (articles, error) in
        self.loadingIndicator.stopAnimating()
        if error == nil {
            self.stories = articles
            self.collectionView.reloadData()
        }
    }
}

在Artikel:

1)改变getArticles函数

代码语言:javascript
复制
static func getArticles(_ category_id: Int, nextPageUrl: String?, completionHandler: @escaping ArrayCompletionHandler) {

    //...

    let new_api = nextPageUrl ?? Config.server_addforarticle + newcategory

    //...
}

2)在此函数中,可以在nextPageUrl中返回ArrayCompletionHandler值。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49512406

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档