UIImageView上的Swift滑动手势根本不起作用
问题描述:
我有以下代码,但除了我尝试的所有内容之外,手势在swipeUpDots上无法识别(控制台中没有“swiped”)。我该怎么办,谢谢!UIImageView上的Swift滑动手势根本不起作用
我在我的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,设置它的框架属性。欲了解更多信息,请参阅文件从苹果:
其实* *不,你*不*需要做任何超过初始化'UIView'如果您使用自动布局。 (在这种情况下,您确实需要将视图的'translatesAutoresizingMaskIntoConstraints'设置为'false'。) – dfd
我不确定OP是否使用自动布局。但谢谢你帮我清理它! –