gpt4 book ai didi

ios - 将手势识别器添加到表格单元格中的 ImageView

转载 作者:搜寻专家 更新时间:2023-10-30 22:21:31 24 4
gpt4 key购买 nike

如何将手势识别器添加到表格单元格中的 UIImageView?我想要这样,如果用户点击单元格中的图像,图像就会改变,数据模型也会更新。

我知道这需要在 UITableViewController 中设置。如果点击单元格中的任何位置,我的代码目前可以执行命令,但我希望它仅在点击图像时执行,而不是单元格中的任何位置。

我在 viewDidLoad 中设置了手势识别器

override func viewDidLoad() {
super.viewDidLoad()

// Load sample data
loadSampleHabits()

// Initialize tap gesture recognizer
var recognizer = UITapGestureRecognizer(target: self, action: #selector(tapEdit(recognizer:)))
// Add gesture recognizer to the view
self.tableView.addGestureRecognizer(recognizer)

这是函数

//action method for gesture recognizer
func tapEdit(recognizer: UITapGestureRecognizer) {
if recognizer.state == UIGestureRecognizerState.ended {
let tapLocation = recognizer.location(in: self.tableView)
if let tapIndexPath = self.tableView.indexPathForRow(at: tapLocation) {
if let tappedCell = self.tableView.cellForRow(at: tapIndexPath) as? HabitTableViewCell {
print("Row Selected")

}
}
}

What the cell looks like

作为次要问题,如果我想向单元格添加手势识别器和单元格内的 ImageView 是否有任何冲突?

最佳答案

您正在根据需要在 tableview 而不是 imageView 上添加手势识别器。你需要将代码从 viewDidLoad 移动到 cellForRowAtIndexPath 并在配置单元格时向每个单元格中的 imageView 添加手势。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
var recognizer = UITapGestureRecognizer(target: self, action: #selector(tapEdit(recognizer:)))
// Add gesture recognizer to your image view
cell.yourimageview.addGestureRecognizer(recognizer)
}

注意:请确保启用 ImageView 的userinteraction

cell.yourimageview.userInteractionEnabled = YES;

根据您的要求,我会建议使用 UILongPressGestureRecognizer,因为它在手势和选择中发生冲突的可能性较小。您可以在 viewDidLoad 中添加 UILongPressGestureRecognizer 并根据您的要求访问它。

let lpgr = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.handleLongPress(_:)))
lpgr.minimumPressDuration = 1
tableView.addGestureRecognizer(lpgr)

定义方法为

func handleLongPress(_ gesture: UILongPressGestureRecognizer){
if gesture.state != .began { return }
let tapLocation = gesture.location(in: self.tableView)
if let tapIndexPath = self.tableView.indexPathForRow(at: tapLocation) {
if let tappedCell = self.tableView.cellForRow(at: tapIndexPath) as? HabitTableViewCell {
print("Row Selected")

}
}

您可以尝试从您的方法中删除 if recognizer.state == UIGestureRecognizerState.ended 条件。

UITapGestureRecognizer 是一个离散的手势,因此,当手势被识别时,您的事件处理程序只会被调用一次。您根本不必检查状态。当然,您不会收到 .Began 状态的电话。有关更多信息,请考虑@Rob ans here .

关于ios - 将手势识别器添加到表格单元格中的 ImageView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45048891/

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