我在xCode中有一个标签,我希望在一个单词和当前时间之间无限淡化。
我已经在网上看过,可以找到一个淡入淡出,但对Swift来说是新手,所以我很难适应我的需要。
任何帮助都会很棒,谢谢!
答案 0 :(得分:1)
以下是如何执行此操作的示例:
@IBOutlet weak var label: UILabel!
@IBAction func fade_out(sender: AnyObject) {
fade(label)
}
@IBAction func reset(sender: AnyObject) {
label.text = "label"
}
func fade(label : UILabel) {
UIView.animateWithDuration(1.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
label.alpha = 0.0
}, completion: nil)
UIView.animateWithDuration(2.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: {
label.alpha = 1.0
label.text = String(NSDate())
}, completion: nil)
}
我所做的是首先使用UIViewAnimationOptions.CurveEaseOut
淡出标签,然后使用UIViewAnimationOptions.CurveEaseIn
将今天的日期再次淡入。
Here是我为您创建的测试项目,您可以看到我是如何完成的。
修改强>
要做无限,你可以这样做,没有按钮
var timer = NSTimer()
var b = false
override func viewDidLoad() {
super.viewDidLoad()
self.timer = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: #selector(ViewController.fade), userInfo: nil, repeats: true)
}
func fade() {
if b{
UIView.animateWithDuration(1.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
self.label.alpha = 0.0
self.label.text = "Label"
}, completion: nil)
UIView.animateWithDuration(1.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: {
self.label.alpha = 1.0
self.label.text = String(NSDate())
}, completion: nil)
b = false
}
else{
UIView.animateWithDuration(1.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
self.label.alpha = 0.0
self.label.text = String(NSDate())
}, completion: nil)
UIView.animateWithDuration(1.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: {
self.label.alpha = 1.0
self.label.text = "Label"
}, completion: nil)
b = true
}
}
答案 1 :(得分:1)
一种更优雅的方式是使用 CAAnimation - >
class YourClass: UIViewController , ..{
@IBOutlet weak var fadingLabel: UILabel!
var a = true
override func viewDidLoad() {
super.viewDidLoad()
NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(ViewController.swapText), userInfo: nil, repeats: true)
let anim : CABasicAnimation = CABasicAnimation(keyPath: "opacity")
anim.fromValue = 1
anim.toValue = 0
anim.duration = 0.5
anim.autoreverses = true
anim.repeatCount = Float.infinity
fadingLabel.layer.addAnimation(anim, forKey: "flashOpacity")
}
func swapText(){
if a == true{
fadingLabel.text = String(NSDate())
a = false
}else{
fadingLabel.text = String("My Text")
a = true
}
}
}
现在你要做的就是在NSTimer()中操纵anim.duration
和timeInterval ......