Reputation: 1
I created a label programmatically, and initially the label don't appear , only when button "appear" is touched (Ok). I want to know how to move the label only once. If the label was moved for the first time, when I touch the button again, nothing must happen.
import UIKit
class ViewController: UIViewController {
var label = UILabel()
var screenWidth: CGFloat = 0.0
var screenHeight: CGFloat = 0.0
override func viewDidLoad() {
super.viewDidLoad()
let screenSize: CGRect = UIScreen.mainScreen().bounds
screenWidth = screenSize.width
screenHeight = screenSize.height
label = UILabel(frame: CGRectMake(0, 64, screenWidth, 70))
label.textAlignment = NSTextAlignment.Center
label.backgroundColor = UIColor.blackColor()
label.text = "Label Appear"
label.font = UIFont(name: "HelveticaNeue-Bold", size: 16.0)
label.textColor = UIColor.whiteColor()
view.addSubview(label)
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.label.center.y -= self.view.bounds.width
}
@IBAction func appear(sender: AnyObject) {
UIView.animateWithDuration(0.5, animations: {
self.label.center.y += self.view.bounds.width
}, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Upvotes: 0
Views: 1112
Reputation: 23
One solution is to add a boolean that indicate if the label has already moved or hasn't.
For example :
var hasLabelAlreadyMoved = false
...
@IBAction func appear(sender: AnyObject) {
/*
We want to move the label if the bool is set to false ( that means it hasn't moved yet ),
else ( the label has already moved ) we exit the function
*/
guard !self.hasLabelAlreadyMoved else {
return
}
self.hasLabelAlreadyMoved = true
UIView.animateWithDuration(0.5, animations: {
self.label.center.y += self.view.bounds.width
}, completion: nil)
}
Upvotes: 2