在自定义视图中定义点击手势时出现无法识别的选择器错误 [Swift]

Unrecognized selector error when defining tap gesture in custom view [Swift]

我正在从 xib 创建自定义视图。我想在内部触摸时关闭视图,但无法识别选择器。我用它作为;

  1. 关闭视图
  2. self.closeView
  3. ToolTipView.closeView

none 他们成功了。你知道我做错了什么吗?


class ToolTipView: UIView {

    @IBOutlet private var contentView:UIView?

    override init(frame: CGRect) { // for using CustomView in code
        super.init(frame: frame)
        self.commonInit()
    }

    required init?(coder aDecoder: NSCoder) { // for using CustomView in IB
        super.init(coder: aDecoder)
        self.commonInit()
    }

    private func commonInit() {
        NSBundle.mainBundle().loadNibNamed("ToolTipView", owner: self, options: nil)
        guard let content = contentView else { return }
        content.frame = self.bounds
        content.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
        self.addSubview(content)
    }

    func showTip(viewToAlign: UIView){

        //some unrelated code

        UIApplication.sharedApplication().keyWindow!.addSubview(contentView!)

        contentView!.userInteractionEnabled = true           
        let tapGesture = UITapGestureRecognizer.init(target: contentView, action: #selector(self.closeView))
        contentView!.addGestureRecognizer(tapGesture)

    }

    func closeView() {
        self.removeFromSuperview()
    }
}

原来是和我说无关代码的部分代码有关。

我正在更改计算自定义视图的相对位置。我正在更改 contentView 的框架,这是错误的部分。相反,我操纵了 self。现在一切如我所愿。

我的函数的工作版本:

func showTip(viewToAlign: UIView, viewToAdd: UIView){

    self.userInteractionEnabled = true

    let relativeFrame = viewToAlign.convertRect(viewToAlign.bounds, toView: nil)
    let relativeCenter = viewToAlign.convertPoint(viewToAlign.bounds.origin, toView: nil)

    self.frame = CGRectMake(relativeFrame.minX - (self.frame.size.width + 5), relativeCenter.y - self.frame.size.height/2 , self.frame.size.width, self.frame.size.height)

    self.layer.masksToBounds = false
    self.layer.shadowOffset = CGSizeMake(0, 0)
    self.layer.shadowRadius = 5
    self.layer.shadowOpacity = 0.5

    viewToAdd.addSubview(self)

    tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(closeView))
    viewToAdd.addGestureRecognizer(tapGesture!)
}