使用collectionView作为容器时,如何插入新屏幕?

时间:2018-08-22 00:47:29

标签: ios swift uicollectionview uicollectionviewcell

我正在尝试创建一个使用collectionView作为其在屏幕之间进行分页的基础的应用程序。对于功能之一,我想在用户点击按钮时插入一个屏幕(collectionView单元格),并在用户再次点击按钮时移除屏幕(collectionView单元格)。我已经尝试实现如下所示的插入和删除方法,但是当它们被调用时,似乎只是将单元格向下滑动而不允许我对其进行修改。当单元格向下滑动时,会产生故障用户体验。如何在不影响用户体验的情况下添加单元修改它,然后将其删除?

下面是添加和删除单元格的代码:

func addCell(sender:Any?){
    self.numberOfItemsInSections += 1
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "customCell", for: IndexPath(item:1,section:0)) as! customCell
    cell.backgroundColor = .purple
    //newCell.label.text = "new cell added"
    self.collectionView.insertItems(at: [IndexPath(item:1,section:0)])

}

func removeCell(sender: Any?) {
    self.numberOfItemsInSections -= 1
    self.collectionView.deleteItems(at: [IndexPath(item:1,section:0)])


}

下面是完整的代码

import UIKit

class ViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,addRemoveCell {


    @IBOutlet weak var collectionView: UICollectionView!

    var numberOfItemsInSections:Int = 3

    var cellType:[String] = ["customCell"]
    var cellClass:[Any]!


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(customCell.self, forCellWithReuseIdentifier: "customCell")
        collectionView.isScrollEnabled = true
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        collectionView.collectionViewLayout = layout
        collectionView.isPagingEnabled = true
    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return numberOfItemsInSections
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: self.view.frame.width, height: self.view.frame.height)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "customCell", for: indexPath) as!  customCell
        cell.addRemoveCellDelegate = self
        cell.label.text = "\(indexPath)"
        cell.backgroundColor = .blue
        return cell
    }

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

    func addCell(sender:Any?){
        self.numberOfItemsInSections += 1
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "customCell", for: IndexPath(item:1,section:0)) as! customCell
        cell.backgroundColor = .purple
        //newCell.label.text = "new cell added"
        self.collectionView.insertItems(at: [IndexPath(item:1,section:0)])

    }

    func removeCell(sender: Any?) {
        self.numberOfItemsInSections -= 1
        self.collectionView.deleteItems(at: [IndexPath(item:1,section:0)])


    }



}

protocol addRemoveCell{
    func addCell(sender:Any?)
    func removeCell(sender:Any?)
}

class customCell:UICollectionViewCell{

    var button:UIButton!
    var label:UILabel!
    var addRemoveCellDelegate:addRemoveCell?
    var addCell:Bool = true

    override init(frame: CGRect) {
        super.init(frame: frame)
         self.button = UIButton(frame: CGRect(x: self.frame.midX, y: self.frame.midX, width: self.frame.midX, height: self.frame.midX))
        self.addSubview(button)


        label = UILabel(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height/8))
        self.addSubview(label)
        label.textAlignment = .center
        label.adjustsFontSizeToFitWidth = true

        label.backgroundColor = .green
        button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
        button.backgroundColor = .orange

        button.translatesAutoresizingMaskIntoConstraints = false
        button.centerXAnchor.constraint(equalTo: self.centerXAnchor, constant: 0).isActive = true
        button.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: 0).isActive = true
        button.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -18).isActive = true
        button.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 18).isActive = true
        button.heightAnchor.constraint(equalToConstant: 70).isActive = true
    }

    @objc func  buttonTapped(){
    print("The button was tapped")
        if addCell{
        if let delegate = addRemoveCellDelegate{
            print("Inside of addCell")
            delegate.addCell(sender: self)
        }
            addCell = !addCell
        }
        else{
            if let delegate = addRemoveCellDelegate{
              delegate.removeCell(sender: self)
            }
            addCell = !addCell
        }
    }

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


} 

0 个答案:

没有答案