以编程方式设置目标时,UITapGestureRecognizer 不起作用
UITapGestureRecognizer not working when setting target programmatically
我正在尝试在 UITableViewCell
内的 UIImageView
上添加点击事件侦听器,所以我在其上添加了一个 UITapGestureRecognizer
并使用了此代码
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
...
cell.editTap.addTarget(self, action: #selector(ProfileTVC.editTapped(sender:)))
//editTap is an UITapGestureRecognizer
...
}
}
func editTapped(sender: UITapGestureRecognizer) {
print("tapped")
if sender.state == UIGestureRecognizerState.ended {
let tapLocation = sender.location(in: self.tableView)
if let tapIndexPath = self.tableView.indexPathForRow(at: tapLocation) {
if fields[tapIndexPath.row].field == "languages_spoken" {
} else if fields[tapIndexPath.row].field == "password" {
} else {
}
}
}
}
但是当我点击我的 UIImageView
时,editTapped
没有被调用。 UIImageView
的用户交互也已启用
您添加的是目标而不是手势
let tapPress = UITapGestureRecognizer(target: self, action: #selector(ProfileTVC. editTapped(_:)))
cell.editTap.addGestureRecognizer(tapPress)
//
@objc func editTapped(_ gestureRecognizer:UIGestureRecognizer)
{
}
您无法使用 "addTarget"
添加 UITapGestureRecognizer
在您的 CellForRowAt 函数中使用此方法更改 addTarget 方法;
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ProfileTVC.editTapped(sender:)))
cell.editTap.addGestureRecognizer(tapGesture) //editTap should be the ImageView inside cell.
我正在尝试在 UITableViewCell
内的 UIImageView
上添加点击事件侦听器,所以我在其上添加了一个 UITapGestureRecognizer
并使用了此代码
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
...
cell.editTap.addTarget(self, action: #selector(ProfileTVC.editTapped(sender:)))
//editTap is an UITapGestureRecognizer
...
}
}
func editTapped(sender: UITapGestureRecognizer) {
print("tapped")
if sender.state == UIGestureRecognizerState.ended {
let tapLocation = sender.location(in: self.tableView)
if let tapIndexPath = self.tableView.indexPathForRow(at: tapLocation) {
if fields[tapIndexPath.row].field == "languages_spoken" {
} else if fields[tapIndexPath.row].field == "password" {
} else {
}
}
}
}
但是当我点击我的 UIImageView
时,editTapped
没有被调用。 UIImageView
的用户交互也已启用
您添加的是目标而不是手势
let tapPress = UITapGestureRecognizer(target: self, action: #selector(ProfileTVC. editTapped(_:)))
cell.editTap.addGestureRecognizer(tapPress)
//
@objc func editTapped(_ gestureRecognizer:UIGestureRecognizer)
{
}
您无法使用 "addTarget"
添加 UITapGestureRecognizer在您的 CellForRowAt 函数中使用此方法更改 addTarget 方法;
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ProfileTVC.editTapped(sender:)))
cell.editTap.addGestureRecognizer(tapGesture) //editTap should be the ImageView inside cell.