按下按钮时,在Swift中的UicollectionViewController中添加单元格

时间:2016-08-12 21:52:21

标签: ios swift uicollectionview cell

在编程方面,我很陌生。我在Swift写作。我有UIcollectionView。我已经在collectionView中创建了一个单元格,您可以在我的代码中看到。问题是我想创建一个像Instagram这样的Feed。所以,当我按下按钮时,我想在UIcollectonView中添加一个单元格。是否可以这样做,如果可以,怎么做?

聚苯乙烯。我没有使用故事板

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






}


}

1 个答案:

答案 0 :(得分:3)

您应该将数据源(如Array<>)附加到UICollectionView以插入单元格;这是因为您在collectionView:numberOfItemsInSection:委托方法中返回了固定数量的单元格(1)。

UICollectionView指定插入新单元格的唯一方法是insertItemsAtIndexPaths:,需要首先更新后面的数据源。

这是一个非常简单的例子:

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

另外,请看一下这个问题和答案:How to insert Cell in UICollectionVIew Programmatically?