我正在研究两个 View ,它们是 UITableViewCell 的子类的子类。在基类(UITableViewCell 的子类)中,我尝试以一种方式设置手势识别器,以便每个父类(super class)都可以更改点击的行为(最终在其委托(delegate)上调用 didTapped 方法)。
我写了以下代码。我可以使用#selector(tap),但是我认为使用变量而不是重写每个父类(super class)中的 tap 方法是一种更简洁的方法。是否可以使用类似 #selector(tapFunc)
的东西?如果不是,从工程角度来看,最干净、最好的解决方案是什么?
class BaseCell: UITableViewCell {
@objc var tapFunc: () -> () = { () in
print("Tapped")
}
@objc func tap() {
print("TEST")
}
func setupBasicViews(withContent: () -> ()) {
let tapGestureRecoginzer = UITapGestureRecognizer(target: self, action: #selector(tapFunc))
contentView.isUserInteractionEnabled = true
contentView.addGestureRecognizer(tapGestureRecoginzer)
}
}
然后是在此 View 之上构建的两个 View :
class ViewA: BaseCell {
//don't want to do this
override func tap() {
//do stuff
}
func setup {
//setup everything else
}
class ViewB: BaseCell {
var delegate: ViewBProtocool?
func setup {
tapFunc = { () in
delegate?.didTapped(self)
}
//setup everything else
}
最佳答案
你离我们并不遥远。进行以下更改:
class BaseCell: UITableViewCell {
var tapFunc: (() -> Void)? = nil
// Called by tap gesture
@objc func tap() {
tapFunc?()
}
func setupBasicViews(withContent: () -> ()) {
let tapGestureRecoginzer = UITapGestureRecognizer(target: self, action: #selector(tap))
contentView.isUserInteractionEnabled = true
contentView.addGestureRecognizer(tapGestureRecoginzer)
}
}
class ViewA: BaseCell {
func setup() {
//setup everything else
}
}
class ViewB: BaseCell {
var delegate: ViewBProtocol?
func setup() {
tapFunc = {
delegate?.didTapped(self)
}
//setup everything else
}
}
现在,每个子类都可以选择为 tapFunc
属性提供闭包。
我在上面展示了 tapFunc
是可选的,基类中没有默认功能。如果需要,请随意更改它以提供一些默认功能。
关于swift - 创建带有函数类型变量的选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54208661/