如何在集合视图单元格中添加uibutton操作?

Chr*_*sen 5 uibutton uicollectionview uicollectionviewcell swift swift3

在此输入图像描述

所以我有这个集合视图,其中包含一个包含编辑按钮的单元格,位于右上角.如何将动作连接到其中?

我尝试添加cell.editbutton.addTargetcollectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell,但它不会检测touchUpInside事件.

Him*_*shu 18

在UICollectionViewCell中创建UIButton的插座,写入

func collectionView(_ collectionView: UICollectionView, 
                    cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    cell.button.tag = indexPath.row
    cell.button.addTarget(self, 
        action: #selector(self.yourFunc(), 
        for: .touchUpInside)
}

func yourFunc(sender : UIButton){
    print(sender.tag)
}
Run Code Online (Sandbox Code Playgroud)

确保为按钮和UICollectionViewCell启用了userInteraction.

  • 如果swift具有Java之类的点击侦听器会更好,那么swift中的所有这些看起来都像拐杖。 (2认同)

iDe*_*per 9

可能需要你 -

写下这段代码 cellForItemAtIndexPath

Swift 2.X

let editButton = UIButton(frame: CGRectMake(0, 20, 40,40))
editButton.setImage(UIImage(named: "editButton.png"), forState: UIControlState.Normal)
editButton.addTarget(self, action: #selector(editButtonTapped), forControlEvents: UIControlEvents.TouchUpInside)

cell.addSubview(editButton)
Run Code Online (Sandbox Code Playgroud)

Swift 3.X

let editButton = UIButton(frame: CGRect(x:0, y:20, width:40,height:40))
editButton.setImage(UIImage(named: "editButton.png"), for: UIControlState.normal)
editButton.addTarget(self, action: #selector(editButtonTapped), for: UIControlEvents.touchUpInside)

cell.addSubview(editButton)
Run Code Online (Sandbox Code Playgroud)

并执行你的行动 -

override func viewDidLoad() {
       super.viewDidLoad()
}

@IBAction func editButtonTapped() -> Void {
    print("Hello Edit Button")
}
Run Code Online (Sandbox Code Playgroud)

  • 我应该在哪里编写 IBAction,应该将其编写在 CollectionViewCell 类中还是 CollectionViewController 中? (2认同)