这很奇怪,但是当我向视图中添加一个UIPanGestureRecognizer时,它就不能工作了。我认为,白色视图是红色视图的一个子视图:

主视图:
@IBOutlet weak var redView: UIView!
@IBOutlet weak var whiteView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let panRecognizer = UIPanGestureRecognizer(target:self, action:#selector(ViewController.handlePan))
whiteView.gestureRecognizers = [panRecognizer]
}
func handlePan(recognizer:UIPanGestureRecognizer) {
//foo
}当我点击并拖动白色视图时,它不会移动。
发布于 2016-04-16 09:32:51
以下是答案:
class ViewController: UIViewController {
@IBOutlet weak var redView: UIView!
@IBOutlet weak var whiteView: UIView!
var lastLocation:CGPoint = CGPointMake(0, 0)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let panRecognizer = UIPanGestureRecognizer(target:self, action:#selector(ViewController.handlePan))
whiteView.addGestureRecognizer(panRecognizer)
}
func handlePan(recognizer:UIPanGestureRecognizer) {
let translation = recognizer.translationInView(redView)
whiteView.center = CGPointMake(lastLocation.x + translation.x, lastLocation.y + translation.y)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
// Promote the touched view
lastLocation = whiteView.center
}
}发布于 2016-04-16 09:23:45
试试这个:
whiteView.isUserInteractionEnabled = true发布于 2019-10-10 13:16:53
来自苹果公司的文档:
如果pan手势识别器的代码未被称为,请检查以下条件是否为真,并根据需要进行更正:
视图的isUserInteractionEnabled属性设置为真。默认情况下,图像视图和标签将此属性设置为false。
minimumNumberOfTouches属性中指定的值与maximumNumberOfTouches属性中指定的值之间有接触的数。
对于UIScreenEdgePanGestureRecognizer对象,边缘属性被配置,并从适当的边缘开始。
https://stackoverflow.com/questions/36662107
复制相似问题