gpt4 book ai didi

swift - 在 collectionview 单元格中添加到 uiview 时点击手势无法按预期工作

转载 作者:可可西里 更新时间:2023-11-01 01:07:56 25 4
gpt4 key购买 nike

我正在以编程方式将点击手势识别器添加到自定义 Collection View 单元格类。出于某种原因,它似乎不起作用。框架不为 0,isUserInteractionEnabled 设置为 true,我确保点击 View 位于所有其他 View 之上:

自定义单元类:

let containerView: UIView = {
let view = UIView()
view.isUserInteractionEnabled = true
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()

let tapView: UIView = {
let v = UIView()
v.isUserInteractionEnabled = true
return v
}()

let tap: UITapGestureRecognizer = {
let t = UITapGestureRecognizer(target: self, action: #selector(tapped))
return t
}()

@objc fileprivate func tapped() {
print("tap")
}

func setTap() {
self.containerView.addSubview(tapView)
tapView.frame = self.frame
// layout constraint code - printing frame shows its not 0 after this

tapView.addGestureRecognizer(tap)
}

在具有 Collection View 的 View Controller 文件中:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! SuggestCell
cell.category.text = data[indexPath.row].category
cell.word.text = data[indexPath.row].word
cell.setTap()
print(cell.tapView.frame)
return cell
}

我确实意识到有一个 didSelectItemAt 方法,但我正在尝试一些自定义行为来检测对单元格的多次点击并执行操作

最佳答案

问题是在您定义的 tap 属性中,self 不是自定义单元格类的实例,因为在创建属性时,对象还没有'已完全初始化。

如果你添加:

print(type(of: self))

对于该代码,您将看到它打印:

(CustomCell) -> () -> CustomCell

而不是所需的:

CustomCell

所以您的目标/操作使用了错误的目标。

解决这个问题的一个简单方法是让 tap 成为一个 lazy var:

lazy var tap: UITapGestureRecognizer = {
let t = UITapGestureRecognizer(target: self, action: #selector(tapped))
return t
}()

然后,当您第一次访问 tap 时,将创建点击手势识别器,此时,您的自定义单元格将被创建并且 self 将引用类的实例。


或者,您可以使 tap 成为一个计算属性:

var tap: UITapGestureRecognizer {
let t = UITapGestureRecognizer(target: self, action: #selector(tapped))
return t
}

tap将在访问时创建并返回一个UITapGestureRecognizer。同样,在这种情况下,将创建自定义单元格,因此 self 将正确引用类的实例。

关于swift - 在 collectionview 单元格中添加到 uiview 时点击手势无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53716478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com