Search code examples
iosswiftswift3core-graphics

How to move line with finger?


I am defining the following variables in my ViewController for a line.

var scanlineRect = CGRect.zero
var scanlineStartY: CGFloat = 0
var scanlineStopY: CGFloat = 0
var topBottomMargin: CGFloat = 30
var scanLine: UIView = UIView()

I can draw a line using UIView and can move it in vertical direction using UIView.animate method. How to move a line dragging it with finger?

func drawLine() 
{
    self.view.addSubview(scanLine)
    scanLine.backgroundColor = UIColor.black
    scanlineRect = CGRect(x: 15, y: 0, width: self.view.frame.width - 30, height: 5)
    scanlineStartY = topBottomMargin
    scanlineStopY = self.view.frame.height - topBottomMargin
    scanLine.frame  = scanlineRect
    scanLine.center = CGPoint(x: scanLine.center.x, y: scanlineStartY)
    scanLine.isHidden = false
}
func Move(Location : CGPoint) 
{
    scanLine.isHidden = false
    weak var weakSelf = scanLine
    UIView.animate(withDuration: 3.0, animations: {
        weakSelf!.center = CGPoint(x: weakSelf!.center.x, y: Location.y)
    }, completion: nil)

}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) 
{    
    var lastPoint = CGPoint.zero
    if let touch = touches.first
    {
        lastPoint = touch.location(in: self.view)
    }
    Move(Location: lastPoint)
}

override func viewDidLoad() 
{
    super.viewDidLoad()
    drawLine()
}

Solution

  • Try using touchesMoved instead of touchesBegan

     override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = touches.first
        guard let location = touch?.location(in: self.view) else{
            return
        }
        scanLine.frame.origin = CGPoint(x: location.x-scanLine.frame.size.width/2, y: location.y-scanLine.frame.size.height/2)
    }
    

    updated

    If you want only move in y axis only you need to change this line

    scanLine.frame.origin = CGPoint(x: location.x-scanLine.frame.size.width/2, y: location.y-scanLine.frame.size.height/2)
    

    use this instead note that scanline.frame.origin.x is unchanged

    scanLine.frame.origin = CGPoint(x: scanLine.frame.origin.x, y: location.y-scanLine.frame.size.height/2)