UICollectionView显示Swift按钮数组

时间:2016-06-10 15:50:24

标签: swift uibutton uicollectionview uicollectionviewcell

我一直试图弄清楚如何使用UICollectionView来显示UIButtons数组。每个按钮都有自己的(不同的)动作,图像,标题等。当按下按钮(覆盖集合视图中的整个单元格)时,该按钮被删除,并执行该动作。我是Swift的新手,不知道从哪里开始,我知道我的代码是错误的,但无论如何我都会添加它:

import UIKit

let reuseIdentifier = "cell"

class CollectionViewController: UICollectionViewController {


var buttons = [UIButton]()
override func viewDidLoad() {
    super.viewDidLoad()


    let button1 = UIButton()
    let button2 = UIButton()
    let button3 = UIButton()
    buttons = [button1,button2,button3]
    button1.addTarget(self, action: #selector(target), forControlEvents: .TouchUpInside)
    button2.addTarget(self, action: #selector(target2), forControlEvents: .TouchUpInside)
    button3.addTarget(self, action: #selector(target3), forControlEvents: .TouchUpInside)
    //haven't added images and titles yet...

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}



override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}


override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of items
    return buttons.count
}

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



    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CollectionViewCell

    cell.button = buttons[indexPath.row]


    return cell
}

细胞分类

import UIKit

class CollectionViewCell: UICollectionViewCell {


@IBOutlet var button: UIButton!

}

2 个答案:

答案 0 :(得分:3)

  1. 我认为将cdr_odbc添加到单元格以触发某些操作是个好主意,因为这可以通过UIButton轻松完成。每个单元格都有一个不必要的额外按钮。如果单元格数量变大,您将拥有一个缓慢的滚动集合视图。
  2. 不是嵌入按钮,而是在collectionView(_:, didSelectItemAtIndexPath:)的实现中,检查部分和项目,并调用本应作为按钮操作的函数。

    1. 我的理解是,无论是集合视图还是表视图,单元格应该是某些数据的图形表示。因此,如果您想让细胞消失,您应该首先消除相应的数据,然后使用collectionView(_:, didSelectItemAtIndexPath:)

答案 1 :(得分:1)

我认为你的代码非常接近。有很多方法可以完成这样的事情。

如果您希望按钮(以及collectionViewCell)消失,您只需从buttons删除该按钮,然后在collectionView上调用reloadData()即可。

如果您想保留collectionView单元格,只需删除按钮,您可以尝试更改按钮定义以保存可选按钮(原始声明未显示在您的代码中),但是像这样:

var buttons : [UIButton?]

然后单击该按钮时,将该按钮更改为nil。调用cellForItemAtIndexPath时,检查按钮是否在数组中,如果不是,只需跳过它(或隐藏它或任何你需要做的事情!)

如果您需要查看更多示例代码,请告诉我们!