我是 swift 的初学者。我正在构建一个单 View 提示计算器应用程序,我只希望在应用程序首次加载时出现一些动画。而且并不是每次我编辑某些内容时都会发生。
这是我的代码: 当应用加载时,我将容器隐藏在 View 之外
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
billView.center.y -= (billView.frame.height)/2
}
并设置向下移动的动画
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
UIView.animateWithDuration(0.8, delay: 0.0,
options: [.CurveEaseOut], animations: {
self.billView.center.y = 210 }, completion: nil)
print(billView.center.y)
}
当应用程序加载时,这可以正常工作。不幸的是,每当我与该应用程序交互时,此动画都会一次又一次地发生。
就像这个动画在调用此函数时发生(即在文本字段上输入任何信息或移动 slider 时)
让 billAmount = NSString(string: billField.text!).doubleValue
var tipPercentages = [0.15, 0.18, 0.22]
let tipPercentage = tipPercentages[segTipControl.selectedSegmentIndex]
let percentLabel = round(tipPercentage * 100)
selectedbillPercentageLabel.text = "+\(percentLabel)%"
let tipAmount = billAmount * tipPercentage
let totalAmount = billAmount + tipAmount
let roundedTotalAmount = round(totalAmount * 100)/100
totalLabel.text = "$\(roundedTotalAmount)"
let splitSelected = Double(splitValueSlider.value)
let intsplitSelected = Int(splitSelected)
splitLabel.text = "\(intsplitSelected)"
let splitDollarAmount = roundedTotalAmount/splitSelected
let roundedSplitDollarAmount = round(splitDollarAmount * 100)/100
splitAmount.text = "$\(roundedSplitDollarAmount)"
有没有办法避免在应用程序中输入任何数据时调用方法 viewDidLayoutSubviews()。
最佳答案
您可以添加一个简单的 bool 翻转来仅显示一次动画,而不是避免调用viewDidLayourSubviews
。添加一个初始化为 false 的 bool 属性;当该属性为 false 时显示动画,并在动画显示后翻转 bool 值。
var animationHasBeenShown = false // class property
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if !animationHasBeenShown {
UIView.animateWithDuration(0.8, delay: 0.0,
options: [.CurveEaseOut], animations: {
self.billView.center.y = 210 }, completion: nil)
print(billView.center.y)
animationHasBeenShown = true
}
}
或者,考虑将动画放置在另一个上下文中;它真的需要在 viewDidLayoutSubviews()
中吗(取决于应用程序的上下文,但可能在 viewDidAppear()
中?)
关于ios - Swift:我怎样才能让动画只发生一次而不是每次我编辑东西时都发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34755229/