簡體   English   中英

在自定義視圖中定義點擊手勢時出現無法識別的選擇器錯誤[Swift]

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

我正在從xib創建一個自定義視圖。 我想在內部觸摸時關閉視圖,但無法識別選擇器。 我用它作為;

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

他們都沒有工作。 你知道我在做什么錯嗎?


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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM