Search code examples
iosswiftuicollectionviewcell

Add cell in UicollectionViewController in Swift when you press a button


I'm pretty new when it comes to programming. I'm writing in Swift. I have a UIcollectionView. I have created a cell in the collectionView as you can see in my code. The thing is that I want to create a feed, like Instagram. So when I press a button do I want to add a cell in the UIcollectonView. Is it possible to do that and if yes, how?

Ps. Im not using the Storyboard

import UIKit
import Firebase
import MapKit

class HomeController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

let cellId = "cellId"

override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Share", style: .Plain, target: self, action: #selector(handleLogout))

    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Logout", style: .Plain, target: self, action: #selector(handleLogout))

    navigationItem.title = "Home"

    collectionView?.alwaysBounceVertical = true

    collectionView?.backgroundColor = UIColor(white: 0.95, alpha: 1)
    collectionView?.registerClass(FeedCell.self, forCellWithReuseIdentifier: cellId)


}

override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 1
}

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    return collectionView.dequeueReusableCellWithReuseIdentifier(cellId, forIndexPath: indexPath)
}

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    return CGSizeMake(view.frame.width, 450)
}

func handleLogout() {

    do {
        try FIRAuth.auth()?.signOut()
    } catch let logoutError {
        print(logoutError)
    }

    let loginContoller = LoginController()
    presentViewController(loginContoller, animated: true, completion: nil)

}

func addFeedCell() {

}



}
class FeedCell: UICollectionViewCell, UICollectionViewDelegateFlowLayout {

var wiindow: UIWindow?
var mapView: MKMapView?

override init(frame: CGRect) {
    super.init(frame: frame)

    setupViews()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

let nameLabel: UILabel = {
    let label = UILabel()
    label.text = "User Name"
    label.font = UIFont.boldSystemFontOfSize(14)
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()

let profileImageView: UIImageView = {
    let imageView = UIImageView()
    imageView.contentMode = .ScaleAspectFit
    imageView.backgroundColor = UIColor.blueColor()
    imageView.translatesAutoresizingMaskIntoConstraints = false
    imageView.layer.cornerRadius = 22
    imageView.layer.masksToBounds = true
    return imageView
}()

let separatorView: UIView = {
    let view = UIView()
    view.backgroundColor = UIColor(red: 192/255, green: 192/255, blue: 192/255, alpha: 1)
    view.translatesAutoresizingMaskIntoConstraints = false
    return view
}()

func setupViews() {

    addSubview(profileImageView)
    addSubview(nameLabel)
    addSubview(separatorView)

    addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-10-[v0(44)]-10-[v1]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": profileImageView, "v1": nameLabel]))

    addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-10-[v0(44)]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": profileImageView]))

    addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-10-[v0]-245-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel]))

    addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": separatorView]))

    addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[v0(1)]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": separatorView]))

    self.wiindow = UIWindow(frame: UIScreen.mainScreen().bounds)
    self.backgroundColor = UIColor(white: 0.95, alpha: 1)

    self.mapView = MKMapView(frame: CGRectMake(0, 70, (self.wiindow?.frame.width)!, 355))
    self.addSubview(self.mapView!)

    self.mapView!.zoomEnabled = false
    self.mapView!.scrollEnabled = false
    self.mapView!.userInteractionEnabled = false






}


}

Solution

  • You should attach a datasource (like an Array<>) to your UICollectionView in order to insert cells; this because you're returning a fixed number of cells (1) in the collectionView:numberOfItemsInSection: delegate method.

    The only method in UICollectionView designated to insert new cells is insertItemsAtIndexPaths: that requires first an update of the datasource behind.

    This is a very simple example:

    var items = ["a", "b", "c"]
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return items.count
    }
    
    func didTapButton() {
        // "logical" insert
        let newChar = "d"
        items.append(newChar)
    
        // "graphical" insert
        let newIndexPath = NSIndexPath(forItem: items.indexOf(newChar)!, inSection: 0)
        collectionView.insertItemsAtIndexPaths([newIndexPath])
    }
    
    //other delegate methods of UICollectionView not implemented in this example
    

    Also, take a look at this question and the answers: How to insert Cell in UICollectionVIew Programmatically?.