gpt4 book ai didi

swift - 如何只移动一次标签(快速)?

转载 作者:行者123 更新时间:2023-11-28 13:01:31 24 4
gpt4 key购买 nike

我以编程方式创建了一个标签,最初标签没有出现,只有当按钮“出现”被触摸时(确定)。我想知道如何只移动标签一次。如果标签是第一次移动,当我再次触摸按钮时,一定不会发生任何事情。

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.
}


}

最佳答案

一种解决方案是添加一个 bool 值,指示标签是否已经移动。

例如:

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)
}

关于swift - 如何只移动一次标签(快速)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33709284/

24 4 0