Writing to Label from Gesture function

Need some help. New to the forum and first post. I'm using the handlePan gesture to move a rectangle on view and is woking. I want to display the center coordinate on real time while moving the rectangle on the label topLabel.text. For some reason when I use: println ("\(view.center.y)") I can see the value update on the output window and all works corrrectly. But if I replace this line with topLabel.text = ("\(view.center.y)") it doesn't work; rectangle don't even move.


class ViewController: UIViewController {


@IBOutlet weak var topLabel: UILabel!


override func viewDidLoad() {

super.viewDidLoad()

}

override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

}


@IBAction func handlePan(recognizer:UIPanGestureRecognizer) {

let translation = recognizer.translationInView(self.view)

if let view = recognizer.view {

view.center = CGPoint(x:view.center.x, y:view.center.y + translation.y)

topLabel.text = "\(view.center.y)"

}

recognizer.setTranslation(CGPointZero, inView: self.view)

}


}


New to swift also, of course.

I can't see anything wrong with your code. It seems you are using Swift 1.x instead of 2. Have you tried the code with Xcode 7 and Swift 2?

I just installed Xcode 7 with swift 2, same results. I'm trying to think on a work around but is just simple to have it there.😕

This is turning me crazy... even with a function I can't grab the origin value into a label. If I uncomment the topLabel.text line it just stop working, still I can see the coordinate with the print line... Any suggestion is appreciated.


import UIKit
class ViewController: UIViewController {
   
    @IBOutlet weak var topLabel: UILabel!
    let centerY = 0
   
   
    override func viewDidLoad() {
        super.viewDidLoad()
        /
       
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        /
    }
    func writeLabel( valor: CGFloat){
       
      print("\(valor)")
//    topLabel.text = "\(valor)"  this line doesn't work
    }
   
   
    @IBAction func handlePan(recognizer:UIPanGestureRecognizer) {
        let translation = recognizer.translationInView(self.view)
        let view = recognizer.view
        let centerY = view!.center.y
        view!.center = CGPoint(x:view!.center.x,
        y:view!.center.y + translation.y)

        writeLabel (centerY)
        recognizer.setTranslation(CGPointZero, inView: self.view)
  
    }
   
}

Setting the topLabel's text causes view to layout it subviews. This means the view that is dragged is reset to a position defined by auto layout contraints.


You can fix this by initializing the dragged view in the code. Then changing the view's center changes auto layout constraints (See UIView translatesAutoresizingMaskIntoConstraints). Or if you want to use interface builder, change view's center auto layout constraints in handlePan method instead of view's center.

Writing to Label from Gesture function
 
 
Q