简体   繁体   English

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

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

I'm creating a custom view from xib. 我正在从xib创建一个自定义视图。 I want to close the view when touched inside but selector is not recognized. 我想在内部触摸时关闭视图,但无法识别选择器。 I used it as; 我用它作为;

  1. closeView closeView
  2. self.closeView self.closeView
  3. ToolTipView.closeView ToolTipView.closeView

none of them worked. 他们都没有工作。 Do you have any idea what am I doing wrong? 你知道我在做什么错吗?


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()
    }
}

It turns out that it was related to part of my code where I said unrelated code. 原来,这与我所说的无关代码有关。

I was changing calculating relative position of my custom view. 我正在更改计算自定义视图的相对位置。 I was changing frame of contentView , which was the wrong part. 我正在更改contentView框架,这是错误的部分。 Instead I manipulated self . 相反,我操纵self Now everything work as I want. 现在一切都按我的意愿进行。

Working version my function: 工作版本我的功能:

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!)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM