背景: 我正在尝试使用BAFluidView为波浪设置动画。我的目标很简单:轻按按钮时启动动画,再次轻按则停止动画。吊舱(上方链接)提供了用于管理此代码的所有代码。
让我知道,我是新来的。请帮助我学习!
我需要为此波创建一个视图。我将其放入名为“ WaveContainer”的函数中。看起来像这样:
func WaveAnimation() {
let wave = BAFluidView(frame: self.view.frame, startElevation: 0.02)!
wave.maxAmplitude = 10
wave.minAmplitude = 8
wave.fillDuration = 50
wave.fill(to: 0.95)
wave.fillAutoReverse = false
wave.fillColor = UIColor.blue
waveView.addSubview(wave)
}
然后我在ViewDidAppear
函数中将此称为。当然可以!我可以看到波浪,它在挥舞。真好
当然,我无法在其他任何地方调用wave
常量! 例如,如果我想按一下按钮停止/开始波浪运动?
如果我尝试将wave
常量从该函数移出到ViewDidLoad
或ViewDidAppear
中,则无法访问...self.view.frame
,并且wave不会出现在屏幕上。
wave
常量? view
引用wave
?非常感谢您的帮助!
import UIKit
import BAFluidView
class ViewController: UIViewController {
// OUTLETS:
@IBOutlet weak var waveView: UIView!
// ACTIONS:
@IBAction func WaveButton(_ sender: UIButton) {
// If the user taps this button and the waveHasStarted variable is equal to false, flip it to true.
if waveHasStarted == false {
print("Start the wave with a press.")
startWave = true
waveHasStarted = true
waveHasBeenStopped = false
} else {
print("Stop the wave with a press.")
startWave = false
waveHasStarted = false
waveHasBeenStopped = true
}
}
// VARIABLES:
var waveHasStarted = false
var startWave = false
var waveHasBeenStopped = true
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {}
// FUNCTIONS:
func WaveAnimation() {
let wave = BAFluidView(frame: self.view.frame, startElevation: 0.02)!
wave.maxAmplitude = 10
wave.minAmplitude = 8
wave.fillDuration = 50
wave.fill(to: 0.95)
wave.fillAutoReverse = false
wave.fillColor = UIColor.blue
// If the variable above has been flipped to "true," start the animation...
if startWave == true {
print("Start that wave animation")
wave.startAnimation()
} else {
// If not, stop it or do nothing.
print("Stop that wave animation")
wave.stopAnimation()
wave.keepStationary()
}
waveView.addSubview(wave)
}
}
答案 0 :(得分:2)
使用lazy
初始化并获得class
级访问权限,
lazy var fluidView: BAFluidView = {
let wave = BAFluidView(frame: self.view.frame, startElevation: 0.02)!
wave.maxAmplitude = 10
wave.minAmplitude = 8
wave.fillDuration = 50
wave.fill(to: 0.95)
wave.fillAutoReverse = false
wave.fillColor = UIColor.blue
return wave
}()
现在您可以在任何地方add
,start
和stop
动画了,
waveView.addSubview(fluidView)
fluidView.startAnimation()
fluidView.stopAnimation()