[英]Not able to add target action to a class UIButton inside a custom View class
[英]Add a target to a UIButton from an external class
我有一个UICollectionViewController( HomeViewController
),其中的每个单元格都包含一个集合视图,并且在每个集合视图的单元格中都有一个button( moreButton
)。 我想向每个按钮添加相同的target( handleMore
),但是目标存在于UICollectionViewController中。
这是我尝试在包含collectionView的单元格类中实现此行为的方式:
cell.moreButton.addTarget(self, action: #selector(HomeViewController.handleMore), for: UIControlEvents.touchUpInside)
另外,还有更好的方法吗? 该按钮可能会显示一个视图控制器。
我认为从cellForRowAtIndexPath:
目标不是一个好主意。 您应该从您的自定义单元类实现一个委托,例如:
Protocol CustomCellDelegate{
func didButtonPressed()
}
并且您需要实例化一个称为委托的变量来实现您单元格的按钮目标:
class CustomCell: UITableViewCell{
/...../
var delegate: CustomCellDelegate? = nil
override func AwakeFromNib(){
super.awakeFromNib()
self.button.addTarget(self, action: #selector(handleMore), for: .touchUpInside)
}
func handleMore(){
if(self.delegate != nil){
self.delegate.didButtonPressed()
}
}
}
这是一个使用ViewController制作东西的示例,因此您首先将单元格的委托设置为self( cell.delegate = self
),其次您必须在ViewController上实现CustomCellDelegate。 否则,如果仅在此自己的单元格中进行更改,则可以使用自定义单元格类中的添加目标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.