我有一个CollectionViewCell,我正在研究它的cellForItemAt方法。我在每个Collection视图单元格中都有一个按钮,它在我的CollectionView中定义了3个不同的部分。
我在下面添加代码来设置按钮目标:cell.buttonView.addTarget(self,action:#selector(buttonPressed(sender :)),用于:UIControlEvents.touchUpInside)
现在,我已经创建了一个新方法:@objc func buttonPressed(sender:UIButton)我在其中为UIAlertController添加一个标题,如:let alertController = UIAlertController(title:,message:“Below actions are”,preferredStyle:.actionSheet)
所以基本上,每次在单元格中点击任何按钮时,警报应该打开,并且每次标题都不同。
我如何动态传递标题?
如果要传递的标题是按钮的标题,那么你可以简单地这样做: -
@objc func buttonPressed(sender: UIButton){
let title = sender.title(for: .normal)
}
如果它是部分中的其他数据,您可以在按钮上使用标记,并将它们设置为indexPath.row: -
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
cell.buttonView.tag = indexPath.row
}
在Button的操作中,访问按钮的标签
@objc func buttonPressed(sender: UIButton){
let objectIndex = sender.tag
let object = yourArray[objectIndex]
let title = object.title
}