本文介绍了如何在Swift中向Collection View Cell添加删除按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
现在我有一个滚动用户名列表,使用按钮的集合视图。但我想为每一行添加重叠的删除按钮。它们需要附加到名称按钮并随之滚动。
Right now I have a list of scrolling usernames using a Collection View of buttons. But I’d like to add overlapping delete buttons to each row. They'd need to be attached to the name buttons and scroll with them.
如何将这些按钮添加到我的CollectionView?
(我还想跳过第一行的删除按钮,原因很明显)
How can I add these buttons to my CollectionView?(Also I'd like to skip the delete button on the first row for obvious reasons)
当前代码:
//Add the cells to collection
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell: UsernameCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! UsernameCollectionViewCell
cell.usernameLabel.text = userNames [indexPath.row]
return cell
}
//Upon Selecting an item
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if (indexPath.row == 0){
self.performSegueWithIdentifier("newUserSegue", sender: self)
}
else {
sendData(userNames[indexPath.row])
self.dismissViewControllerAnimated(true, completion: nil)
}
}
推荐答案
搞定了!方法如下:
- 我在故事板中为单元格添加了一个按钮。
- 连接出口到UICollectionViewCell类。
-
编辑的视图控制器代码:
- I added a button to the cell in the Storyboard.
- Connected an outlet to the UICollectionViewCell class.
Edited view controller code to:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell: UsernameCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! UsernameCollectionViewCell
cell.usernameLabel.text = userNames [indexPath.row]
cell.deleteButton?.layer.setValue(indexPath.row, forKey: "index")
cell.deleteButton?.addTarget(self, action: "deleteUser:", forControlEvents: UIControlEvents.TouchUpInside)
// Remove the button from the first cell
if (indexPath.row == 0){
var close : UIButton = cell.viewWithTag(11) as! UIButton
close.hidden = true
}
return cell
}
func deleteUser(sender:UIButton) {
let i : Int = (sender.layer.valueForKey("index")) as! Int
userNames.removeAtIndex(i)
UserSelectCollection.reloadData()
}
非常感谢JigarM在GitHub上的例子:
Many thanks to JigarM for his examples on GitHub:https://github.com/JigarM/UICollectionView-Swift
这篇关于如何在Swift中向Collection View Cell添加删除按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!