我在stackoverflow上提出了一个问题,并得到了一个完整的答案。
要获取UIPanGestureRecognizer
的起点和终点,请使用代码:
var view = UIView()
func panGestureMoveAround(gesture: UIPanGestureRecognizer) {
var locationOfBeganTap: CGPoint
var locationOfEndTap: CGPoint
if gesture.state == UIGestureRecognizerState.Began {
locationOfBeganTap = gesture.locationInView(view)
} else if gesture.state == UIGestureRecognizerState.Ended {
locationOfEndTap = gesture.locationInView(view)
}
}
为了更好地观看,我会绘制一个捕捉起点的矩形并自动调整大小以完成移动。
我如何绘制一个矩形作为起点并按照我的动作结束手势?
答案 0 :(得分:4)
你需要创建一个UIView的子类,像RectView一样调用它,就像这样:
@IBDesignable
class RectView: UIView {
@IBInspectable var startPoint:CGPoint?{
didSet{
self.setNeedsDisplay()
}
}
@IBInspectable var endPoint:CGPoint?{
didSet{
self.setNeedsDisplay()
}
}
override func drawRect(rect: CGRect) {
if (startPoint != nil && endPoint != nil){
let path:UIBezierPath = UIBezierPath(rect: CGRectMake(min(startPoint!.x, endPoint!.x),
min(startPoint!.y, endPoint!.y),
fabs(startPoint!.x - endPoint!.x),
fabs(startPoint!.y - endPoint!.y)))
path.stroke()
}
}
}
然后在您的视图控制器中,您可以说:
@IBAction func panGestureMoveAround(sender: UIPanGestureRecognizer) {
var locationOfBeganTap: CGPoint
var locationOfEndTap: CGPoint
if sender.state == UIGestureRecognizerState.Began {
locationOfBeganTap = sender.locationInView(rectView)
rectView.startPoint = locationOfBeganTap
rectView.endPoint = locationOfBeganTap
} else if sender.state == UIGestureRecognizerState.Ended {
locationOfEndTap = sender.locationInView(rectView)
rectView.endPoint = sender.locationInView(rectView)
} else{
rectView.endPoint = sender.locationInView(rectView)
}
}