如果集合视图单元格中的计数 > 8,则添加额外的单元格作为“查看更多”

问题描述 投票:0回答:2

我有一个 UICollectionView。我从我的 URL 动态显示集合视图中的单元格。我设置了单元格的宽度和高度,单行中只能有 4 个单元格。现在从我的 url 中,我总共获得了 14 件商品。我的意思是 14 个标签名称和该标签的 14 个图像。所以总共 14 个项目必须显示在我的表格视图中。

但我需要的是:我需要在集合视图中仅显示两行,并设置单元格的宽度和高度。所以每行 4 个项目意味着两行总共 8 个项目。但从我的 URL 中我得到了 14 个项目,对吧?.

所以,我需要的是 - 如果项目数超过 7。我正在从 0 到 7 进行计数。然后我需要将第 7 个单元格显示为静态。文本应自动更改为“查看更多”。

如何做到这一点?

import UIKit

class HomeViewController: UIViewController ,UICollectionViewDataSource, UICollectionViewDelegate {


    @IBOutlet weak var collectionView1: UICollectionView!


    var BTdata = [BTData]()


    override func viewDidLoad()
    {
        super.viewDidLoad()

        ListBusinessTypes()

    }

    // Values from Api for Business Types
    func ListBusinessTypes()
    {
        let token = NSUserDefaults.standardUserDefaults().valueForKey("access_token") as! String

        let headers = ["x-access-token": token]

        let request = NSMutableURLRequest(URL: NSURL(string: “some url“)!,
                                          cachePolicy: .UseProtocolCachePolicy,
                                          timeoutInterval: 10.0)
        request.HTTPMethod = "GET"
        request.allHTTPHeaderFields = headers

        let session = NSURLSession.sharedSession()
        let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
            if (error != nil)
            {
                print(error)

                let ErrorAlert = UIAlertController(title: "Error", message: "Problem with internet connectivity or server, please try after some time", preferredStyle: UIAlertControllerStyle.Alert)

                // add an action (button)
                ErrorAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))

                // show the alert
                self.presentViewController(ErrorAlert, animated: true, completion: nil)
            }
            else
            {
                if let json = (try? NSJSONSerialization.JSONObjectWithData(data!, options: [])) as? Dictionary<String,AnyObject>
                {
                    let success = json["success"] as? Int

                    if(success == 1)
                    {

                        if let typeValues = json["data"] as? [NSDictionary]
                        {
                            dispatch_async(dispatch_get_main_queue(),{

                                for item in typeValues
                                {
                                    self.BTdata.append(BTData(json:item))
                                }

                                self.collectionView1!.reloadData()
                            })
                        }
                    }
                    else
                    {
                        let message = json["message"] as? String

                        print(message)

                        let ServerAlert = UIAlertController(title: "Error", message: message, preferredStyle: UIAlertControllerStyle.Alert)

                        // add an action (button)
                        ServerAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))

                        // show the alert
                        self.presentViewController(ServerAlert, animated: true, completion: nil)
                    }
                }
            }
        })

        dataTask.resume()
    }

       func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
          return BTdata.count

    }


    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
    {

            let cell: collview1 = collectionView.dequeueReusableCellWithReuseIdentifier("Cell1", forIndexPath: indexPath) as! collview1
            cell.lblCellA.text = BTdata[indexPath.row].BTNames

            cell.imgCellA.image = UIImage(named: tableImages[indexPath.row])


            return cell


    }




      collection view cell space and size
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
    {


            return CGSizeMake((self.view.frame.size.width/4) - 10, (self.view.frame.size.width/4) - 15);

    }



}
ios swift uicollectionview
2个回答
2
投票

首先不返回

BTdata.count
,如果超过8则返回8。

return BTdata.count>8 ?  8 : BTdata.count;

接下来在 UI 编辑器中添加另一种类型的单元格,为其命名(例如

SeeMore
),然后修改集合视图项处理程序,以便它为最后一行返回适当的单元格:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
  if indexPath.row==7 {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("SeeMore", forIndexPath: indexPath)
    return cell       
  } else {
    let cell: collview1 = collectionView.dequeueReusableCellWithReuseIdentifier("Cell1", forIndexPath: indexPath) as! collview1
    cell.lblCellA.text = BTdata[indexPath.row].BTNames
    cell.imgCellA.image = UIImage(named: tableImages[indexPath.row])
    return cell
  }
}

并在

collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
方法中相应地返回该单元格的适当大小。


0
投票

实现计数功能如下:

 func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
          return BTdata.count > 7 ? 8 : BTdata.count
    }

还有

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("SeeMore", forIndexPath: indexPath) as! collview1
      if indexPath.row==7 {
        cell.lblCellA.text = "See More"
      } else {
        cell.lblCellA.text = BTdata[indexPath.row].BTNames
        cell.imgCellA.image = UIImage(named: tableImages[indexPath.row])
      }
return cell
    }
© www.soinside.com 2019 - 2024. All rights reserved.