我有以下视图(这是整个视图控制器的子视图):
lazy var superView: UIView = {
let cv = UIView()
cv.backgroundColor = .gray
cv.translatesAutoresizingMaskIntoConstraints = false
cv.layer.cornerRadius = 5
cv.layer.masksToBounds = true
cv.isUserInteractionEnabled = true
cv.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(handlePan)))
return cv
}()
这是我为它设置约束的地方:
// constraints for super view
func setupSuperView() {
superView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
superView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
superView.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -24).isActive = true
superView.heightAnchor.constraint(equalTo: view.heightAnchor, constant: -200).isActive = true
// ISSUE: For some reason, adding this subview with or without constraints screws up the pan functionality of the superview
superView.addSubview(subView)
}
这是我添加到superView内部的子视图(我将其视为容器视图):
lazy var subview: UIImageView = {
let sv = UIImageView()
sv.translatesAutoresizingMaskIntoConstraints = false
sv.contentMode = .scaleAspectFill
return sv
}()
其约束:
// constraints for yes/no view within superview
func setupSubView() {
subView.centerXAnchor.constraint(equalTo: superView.centerXAnchor).isActive = true
subView.centerYAnchor.constraint(equalTo: superView.centerYAnchor).isActive = true
}
最后,我在这里建立了平移手势的功能:
// pan functionality for swiping on superview
func handlePan(gesture: UIPanGestureRecognizer) {
guard let superview = gesture.view else {
return
}
// point you are tapped on
let point = gesture.translation(in: view)
// reference for how far left or right of the center of the superview your pan is
let xFromCenter = superview.center.x - view.center.x
// allows the superview to move with your finger
superview.center = CGPoint(x: view.center.x + point.x, y: view.center.y + point.y)
// dragged right
if xFromCenter > 0 {
subView.image = #imageLiteral(resourceName: "yes")
subView.tintColor = UIColor.green
// else dragged left
} else {
subView.image = #imageLiteral(resourceName: "no")
subView.tintColor = UIColor.red
}
// when you let go
if gesture.state == UIGestureRecognizerState.ended {
// animate superview back to center where it originally was
UIView.animate(withDuration: 0.2) {
superview.center = self.view.center
}
}
}
在我添加子视图之前(当我发表评论时),pan手势在superview上运行得非常好。但是,当我将子视图限制在超视图的中心并尝试在视图控制器周围移动超视图时,它的行为很奇怪(只能向左移动,向右移动时不断向后移动)。 / p>
非常感谢任何和所有帮助。
答案 0 :(得分:1)
在您的子视图上停用userinteraction
,我认为它会起作用!
你的代码应该是,
subView.isUserInteractionEnabled = false
答案 1 :(得分:0)
我想出了这个问题。虽然我不知道这是解决方法的原因,但问题在于我用于平移容器视图的“否”选项所使用的图像导致整个视图行为奇怪,因为它是一个不同的形象。
我通过将两个选项都设置为“是”进行了测试,无论您是向左还是向右平移视图。这解决了导致我认为问题是图像被切换的问题,这取决于您是向左还是向右滑动。我不知道为什么显示两个不同的图像有问题,但我也会尝试解决这个问题。
感谢所有有用的输入!