gpt4 book ai didi

ios - 如何将目标添加到 UIImageView 的封闭初始化中

转载 作者:行者123 更新时间:2023-11-30 11:58:42 25 4
gpt4 key购买 nike

这是初始化UIImageView的代码

  var supportButton: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "Menu3")
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = UIViewContentMode.scaleAspectFill

//Add target here??

imageView.isUserInteractionEnabled = true
return imageView
}()

以下内容不起作用,因为没有 self :

   imageView.addGestureRecognizer(UIGestureRecognizer(target: self(), action: #selector(Support)))

最佳答案

假设您要声明 ViewController 的属性,您需要使用 self 而不是 self()

这是一个例子

class ViewController: UIViewController {

let supportButton: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "Menu3")
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFill
let gestureRecognizer = UIGestureRecognizer(target: self, action: #selector(ViewController.didTouchSupport(gestureRecognizer:)))
imageView.addGestureRecognizer(gestureRecognizer)
imageView.isUserInteractionEnabled = true
return imageView
}()

@objc func didTouchSupport(gestureRecognizer:UIGestureRecognizer) {

}
}

更新

以下代码应该回答您在下面发布的评论。

class TableViewController: UITableViewController {

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! Cell
cell.delegate = self
return cell
}
}

extension TableViewController: CellDelegate {
func didTapSupport() {
// TODO: your custom code goes here
}
}

protocol CellDelegate {
func didTapSupport()
}

class Cell: UITableViewCell {

var delegate: CellDelegate?

let supportButton: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "Menu3")
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFill
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(Cell.didTouchSupport(gestureRecognizer:)))
imageView.addGestureRecognizer(gestureRecognizer)
imageView.isUserInteractionEnabled = true
return imageView
}()

@objc func didTouchSupport(gestureRecognizer:UIGestureRecognizer) {
delegate?.didTapSupport()
}
}

关于ios - 如何将目标添加到 UIImageView 的封闭初始化中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47496118/

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