我以编程方式创建了一个标签,并且只有当触摸“显示”按钮时才会出现标签(确定)。我想知道如何只移动标签一次。如果标签第一次移动,当我再次触摸按钮时,不会发生任何事情。
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.
}
}
答案 0 :(得分:2)
一种解决方案是添加一个布尔,指示标签是否已经移动或没有移动。
例如:
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)
}