简体   繁体   English

如何以编程方式将手势识别器添加到自定义 UIView (XIB)?

[英]How to add gesture recognizer to custom UIView (XIB) programmatically?

Intro介绍

I trying to adding a tap recognizer to an instance of my custom UIView class CardView .我试图将点击识别器添加到我的自定义UIViewCardView的实例中。 So I created a custom view xib and link my Swift class file CardView.swift via File's Owner .所以我创建了一个自定义视图xib并通过File's Owner链接我的 Swift 类文件CardView.swift After that I connected each outlet to the corresponding UI elements.之后,我将每个插座连接到相应的 UI 元素。

I would like to add my custom View CardView programmatically to my ViewController and attach a tapGesture to the newly created view.我想以编程方式将我的自定义视图CardView添加到我的 ViewController 并将 tapGesture 附加到新创建的视图。

CardView class: CardView 类:

class CardView: UIView {

    // Delcare outlets
    @IBOutlet var view: UIView!
    @IBOutlet weak var title: UILabel!
    @IBOutlet weak var icon: UIImageView!


    //MARK: Initialization
    override init(frame: CGRect) {
        super.init(frame: frame)

        Bundle.main.loadNibNamed("CardView", owner: self, options: nil)
        addSubview(view)
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
    }

}

ViewController class视图控制器类

In the viewDidLoad() function of ViewController.swift I created an instance of CardView():在 ViewController.swift 的viewDidLoad()函数中,我创建了一个 CardView() 实例:

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let cardView = CardView()
        self.view.addSubview(cardView)

        // Style cardView instance
        cardView.view.backgroundColor = UIColor.yellow
        cardView.view.center.x = self.view.center.x
        cardView.view.center.y = self.view.center.y

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(gestureRecognizer:)))
        cardView.addGestureRecognizer(tapGesture)

    }

Than I add tapGesture to my cardView just like normal using Swift:然后我像往常一样使用 Swift 将 tapGesture 添加到我的cardView

let tapGesture = UIPanGestureRecognizer(target: self, action: #selector(handleTap(gestureRecognizer:)))    cardView.addGestureRecognizer(panGesture)

And add the corresponding function to be called:并添加相应的要调用的函数:

func handleTap(gestureRecognizer: UIGestureRecognizer) {
        let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
        self.present(alert, animated: true, completion: nil)
    }

Main question/problem主要问题/问题

The problem that I have with adding a tap Gesture Recognizer to the newly created CardView - an instance of the CardView - is that the function handleTap() is never been called.我在向新创建的 CardView(CardView 的一个实例)添加点击手势识别器时遇到的问题是函数handleTap()从未被调用。

I already tried several things like add cardView.isUserInteractionEnabled = true to both files ( ViewController.swift and CardView.swift class).我已经尝试了几种方法,例如向两个文件( ViewController.swiftCardView.swift类)添加cardView.isUserInteractionEnabled = true Also add in one of these files and not in the other one.还要添加这些文件之一,而不是另一个。

After declaring the type of gesture, I also try to add it my the super view, the one that is linked with the ViewController.swift file .声明手势类型后,我还尝试将其添加到超级视图中,即与ViewController.swift file链接的视图。 When I tap on the screen, the function will be triggered, but not with my own created custom UIView.当我点击屏幕时,将触发该功能,但不会触发我自己创建的自定义 UIView。

Beside those I also tried to add UIGestureRecognizerDelegate to my VC class with no result.除了这些,我还尝试将UIGestureRecognizerDelegate添加到我的 VC 类中,但没有结果。

class ViewController: UIViewController, UIGestureRecognizerDelegate {}

In my viewDidLoad() function before I connect the gesture to my cardView I added this extra line: tapGesture.delegate = self .在我将手势连接到我的cardView之前的viewDidLoad()函数中,我添加了以下额外的行: tapGesture.delegate = self

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(gestureRecognizer:)))
tapGesture.delegate = self
architectView.addGestureRecognizer(tapGesture)

I had same issue with Custom UIView.我对自定义 UIView 有同样的问题。

I made Xib and swift file and connected it.我制作了Xibswift文件并连接了它。 Then add gesture to UIView, however, it doesn't work.然后给 UIView 添加手势,但是,它不起作用。 I changed UIView to UIButton to solve the problem but doesn't work.我将 UIView 更改为 UIButton 以解决问题但不起作用。

To solve my problem is解决我的问题是

AutoLayout Problem自动布局问题

When I run the app and debug by Debug view hierarchy , there is ambiguous problem with my customUIView.当我运行应用程序并通过Debug view hierarchy进行调试时,我的 customUIView 存在不明确的问题。

By print description of UIView, I can notify it has frame(0,0), subView has own frame on the other hand.通过 UIView 的打印描述,我可以通知它有 frame(0,0),另一方面 subView 有自己的 frame。

So I delete and make from the scratch, run test each time and solve it.所以我从头开始删除和制作,每次运行测试并解决它。 Also gesture function works when clicked custom UIView.单击自定义 UIView 时,手势功能也有效。

I hope this works to you.我希望这对你有用。 I saw your code and it doesn't seem have problem from your code, so check xib file and auto layout those label and image.我看到了您的代码,您的代码似乎没有问题,因此请检查 xib 文件并自动布局这些标签和图像。

更正UIPanGestureRecognizer(target: self, action: #selector(dragged))

UIPanGestureRecognizer(target: self, action: #selector(dragged(sender:)))

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

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