如何将目标添加到UIImageView

时间:2017-11-26 12:21:20

标签: ios swift uiimageview

这是初始化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
}()

因为没有自我,所以没有工作:

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

1 个答案:

答案 0 :(得分:0)

假设您要声明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()
    }
}