【问题标题】:UICollectionView showing array of buttons SwiftUICollectionView 显示按钮数组 Swift
【发布时间】:2016-06-10 15:50:24
【问题描述】:

我一直试图弄清楚如何使用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!

}

【问题讨论】:

  • 当你点击按钮时,只有按钮消失,还是整个单元格消失?
  • 只有按钮,我正在考虑从动作函数中的数组中删除按钮。还是删除单元格是更好的方法?

标签: swift uibutton uicollectionview uicollectionviewcell


【解决方案1】:
  1. 我认为将UIButton 添加到单元格以触发某些操作不是一个好主意,因为这可以通过collectionView(_:, didSelectItemAtIndexPath:) 轻松完成。每个单元格都会有一个不必要的额外按钮。如果单元格计数变大,您将看到滚动缓慢的集合视图。

collectionView(_:, didSelectItemAtIndexPath:) 的实现中,不是嵌入按钮,而是检查部分和项目,并调用本来是按钮操作的函数。

  1. 我的理解是,无论是集合视图还是表格视图,单元格都应该是一些数据的图形表示。所以如果要让单元格消失,你应该先把对应的数据消失,然后使用deleteItemsAtIndexPaths

【讨论】:

    【解决方案2】:

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

    如果您希望按钮(和collectionViewCell)消失,您只需从buttons 中删除该按钮并在collectionView 上调用reloadData()

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

    var buttons : [UIButton?]
    

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

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

    【讨论】:

    • 我认为代码行“cell.button = buttons[indexPath.row]”是错误的。因为在按下第一个(或任何一个)按钮时不会调用 button1 的操作
    猜你喜欢
    • 2020-04-30
    • 1970-01-01
    • 2015-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-05
    相关资源
    最近更新 更多