user5513630
user5513630

Reputation: 1699

Add extra cell as "see more" if count is > 8 in collection view cell

I have one UICollectionView. I am dynamically showing the cell in my collection view from my URL. I set the cell width and height that only 4 cell should be in single row. So now from my url, I am getting totally 14 items. I means 14 label name and 14 image for that label. So totally 14 items have to be displayed in my table view.

But what I need is : I need to show only two row in my collection view and I set the width and height for cell. So per row 4 items means, two row totally 8 items. But from my URL I am getting 14 items right?.

So, what I need is - if the items count is more that 7. I am counting form 0 to 7. Then I need to show the 7th cell as static like.The text should be automatically change to “see more”.

How to do that?

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);

    }



}

Upvotes: 1

Views: 1229

Answers (1)

Jean-Baptiste Yun&#232;s
Jean-Baptiste Yun&#232;s

Reputation: 36431

First don't return BTdata.count but 8 if it is more than 8.

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

Next add another type of cell in UI editor, give it a name (say SeeMore, and modify the collection view item handler so that it returns the appropriate one for the last row:

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
  }
}

and return the appropriate size of that cell accordingly in the collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize method.

Upvotes: 2

Related Questions