2016-10-01 17 views
0

我使用下面顯示的代碼讓用戶觸摸並繪製。在觸摸它時,用戶總是離開CGPoint或他/她的第一次和最後一次觸摸的座標。Swift:如何從Override func中取出CGPoint號碼?

var lastPoint: CGPoint! 
var firstPoint: CGPoint! 
var swiped: Bool! 
var allowTouches = true 



override func touchesBegan(touches: Set<UITouch>, 
         withEvent event: UIEvent?) { 
    guard allowTouches else { 
     return 
    } 


    swiped = false 
    if let touch = touches.first { 
    lastPoint = touch.locationInView(self.imageView) 
     firstPoint = lastPoint 

    } 

} 


override func touchesMoved(touches: Set<UITouch>, 
          withEvent event: UIEvent?) { 

    guard allowTouches else { 
     return 
    } 


    swiped = true; 

    if let touch = touches.first { 

     let currentPoint = touch.locationInView(imageView) 
     UIGraphicsBeginImageContext(self.imageView.frame.size) 
     self.imageView.image?.drawInRect(CGRectMake(0, 0, self.imageView.frame.size.width, self.imageView.frame.size.height)) 

     CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y) 
     CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y) 
     CGContextSetLineCap(UIGraphicsGetCurrentContext(),CGLineCap.Round) 
     CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0) 

     CGContextStrokePath(UIGraphicsGetCurrentContext()) 
     self.imageView.image = UIGraphicsGetImageFromCurrentImageContext() 
     UIGraphicsEndImageContext() 


     lastPoint = currentPoint 

      } 

     } 

正如你在當用戶觸摸屏幕,然後滑動,然後取出觸摸後,lastPoint節省座標是節省羅克韋爾FirstPoint座標代碼中看到。

我的問題:我怎麼能得到這兩個座標(firstPoint和lastPoint)作爲返回從重寫func?這樣我可以將這兩個值用於override func之外的其他計算。

+1

你是什麼意思「拉出這兩個座標?」 – NobodyNada

+0

你的問題根本不清楚。請嘗試更好地解釋你正在嘗試做什麼。 – rmaddy

+0

這兩個變量是實例變量。你可以在任何實例方法中使用它們。除了你已經在做的事情之外,你無需做任何事情。也許你應該用你正在嘗試做的事來更新你的問題。 – rmaddy

回答

0

使用

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) 

方法來計算觸摸lastPoint當用戶拿起他的手指。既然你已經將它們聲明爲var和全局變量,因此你可以在類的任何函數(方法)中使用它們。只需計算lastPoint和firstPoint之間的差異,即可獲得距離。