Swift UIImageView 上的滑动手势根本不起作用

Swift swipe gesture on UIImageView is not working at all

我有以下代码,但除了我尝试过的所有内容外,手势在 swipeUpDots 上无法识别(控制台中没有 "swiped")。我该怎么办,谢谢!

我的 viewDidLoad 函数中有 setupInputComponents() 并且调用正确。

func setupInputComponents() {

    let containerView = UIView()

    view.addSubview(containerView)

    let swipeUpDots = UIImageView()

    swipeUpDots.image = #imageLiteral(resourceName: "threeDots")

    swipeUpDots.contentMode = .scaleAspectFit

    containerView.addSubview(swipeUpDots)

    // Adding swipe functionality

    let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(getSwipedUp(swipeGestureRecognizer:)))

    swipeUpDots.addGestureRecognizer(swipeUp)

    swipeUpDots.isUserInteractionEnabled = true

}

@objc func getSwipedUp(swipeGestureRecognizer: UISwipeGestureRecognizer){

    print("swiped")

    if swipeGestureRecognizer.direction == .up {

        print("Up Swiped")

        // Send Message



    }

}

您需要为您的 UISwipeGestureRecognizer 设置允许的方向。你的情况:

swipeUp.direction = .up

此外,我注意到您已经初始化了 containerView (UIView) 和 swipeUpDots (UIImageView),但没有定义它们的框架。以编程方式创建新的 UIView 时,您需要告诉系统在哪里绘制它以及矩形大小应该是多少。这是一个例子:

let rect = CGRect(x: 100, y: 100, width: 100, height: 100)
let containerView = UIView(frame: rect)

对于 imageView,设置其框架 属性。有关详细信息,请参阅 Apple 的文档:

UISwipeGestureRecognizer

UIView

UIImageView