ios 如何使按钮闪烁或闪烁?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34666136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 08:32:57  来源:igfitidea点击:

How to make a button flash or blink?

iosswiftuibutton

提问by alex

I am trying to change a button's color (just a flash/blink) to green when a scan is correct and red when there's a problem. I am able to do this with a view like so

我试图在扫描正确时将按钮的颜色(只是闪烁/闪烁)更改为绿色,在出现问题时将其更改为红色。我能够以这样的观点来做到这一点

func flashBG(){
    UIView.animateWithDuration(0.7, animations: {
        self.view.backgroundColor = UIColor.greenColor()

    })
}

But with a button it stays green

但是有一个按钮它会保持绿色

func flashBtn(){
    UIButton.animateWithDuration(0.5, animations: {
        self.buttonScan.backgroundColor = UIColor.greenColor()
    })
}

I have created the button by code

我已经通过代码创建了按钮

func setupScanButton() {
    let X_Co = (self.view.frame.size.width - 100)/2
    let Y_Co = (self.viewForLayer.frame.size.height + 36/2)

    buttonScan.frame = CGRectMake(X_Co,Y_Co,100,100)
    buttonScan.layer.borderColor = UIColor.whiteColor().CGColor
    buttonScan.layer.borderWidth = 2
    buttonScan.layer.cornerRadius = 50
    buttonScan.setTitle("Scan", forState: .Normal)
    buttonScan.backgroundColor = UIColor.blueColor()
    buttonScan.addTarget(self, action: "buttonScanAction", forControlEvents: .TouchUpInside)
    buttonScan.setTitleColor(UIColor(red:255/255, green: 255/255, blue:255/255, alpha: 1), forState: UIControlState.Normal)

    self.view.addSubview(buttonScan)
}

Should i call setupScanButton() again?

我应该再次调用 setupScanButton() 吗?

采纳答案by Danial Hussain

I hope that will solve your problem.

我希望这能解决你的问题。

buttonScan.alpha = 1.0
UIView.animate(withDuration: 1.0, delay: 1.0, options: UIView.AnimationOptions.curveEaseOut, animations: {

    buttonScan.alpha = 0.0

}, completion: nil) 

回答by Erik Peruzzi

This should work in Swift 4

这应该适用于 Swift 4

extension UIView{
     func blink() {
         self.alpha = 0.2
         UIView.animate(withDuration: 1, delay: 0.0, options: [.curveLinear, .repeat, .autoreverse], animations: {self.alpha = 1.0}, completion: nil)
     }
}

回答by Rashwan L

This will start and stop a flashing button onClick, if you only want to flash the button immediately just use the first statement.

这将启动和停止闪烁的按钮onClick,如果您只想立即使按钮闪烁,只需使用第一条语句。

var flashing = false

@IBAction func btnFlash_Clicked(sender: AnyObject) {
        if !flashing{
            self.buttonScan.alpha = 1.0
            UIView.animateWithDuration(0.5, delay: 0.0, options: [.CurveEaseInOut, .Repeat, .Autoreverse, .AllowUserInteraction], animations: {() -> Void in
                self.buttonScan.alpha = 0.0
                }, completion: {(finished: Bool) -> Void in
            })

            flashing = true
        }
    else{
        UIView.animateWithDuration(0.1, delay: 0.0, options: [.CurveEaseInOut, .BeginFromCurrentState], animations: {() -> Void in
            self.buttonScan.alpha = 1.0
            }, completion: {(finished: Bool) -> Void in
        })
    }
}

Swift 5.x version

斯威夫特 5.x 版本

An updated version with extension.

带有extension.

extension UIView {
    func blink(duration: TimeInterval = 0.5, delay: TimeInterval = 0.0, alpha: CGFloat = 0.0) {
        UIView.animate(withDuration: duration, delay: delay, options: [.curveEaseInOut, .repeat, .autoreverse], animations: {
            self.alpha = alpha
        })
    }
}

To call the function:

调用函数:

button.blink() // without parameters
button.blink(duration: 1, delay: 0.1, alpha: 0.2) // with parameters

回答by Alessandro Ornano

Swift 4:

斯威夫特 4

I've maked an extension with some useful options:

我已经使用一些有用的选项进行了扩展:

extension UIButton {
    open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        return self.bounds.contains(point) ? self : nil
    }
    func blink(enabled: Bool = true, duration: CFTimeInterval = 1.0, stopAfter: CFTimeInterval = 0.0 ) {
        enabled ? (UIView.animate(withDuration: duration, //Time duration you want,
            delay: 0.0,
            options: [.curveEaseInOut, .autoreverse, .repeat],
            animations: { [weak self] in self?.alpha = 0.0 },
            completion: { [weak self] _ in self?.alpha = 1.0 })) : self.layer.removeAllAnimations()
        if !stopAfter.isEqual(to: 0.0) && enabled {
            DispatchQueue.main.asyncAfter(deadline: .now() + stopAfter) { [weak self] in
                self?.layer.removeAllAnimations()
            }
        }
    }
}

First of all, I've overrided the hittestfunction to enablingthe touchalso when the button have the alphaequals to 0.0(transparent) during the animation.

首先,我overrided的hittest功能,以使触摸也当按钮有alpha等于0.0透明动画时)。

Then , all input vars have a default valueso you can launch the blink()method without parameters

然后,所有输入变量都有一个默认值,因此您可以在blink()没有参数的情况下启动该方法

I've introduced also the enabledparameter to start or stop the animations on your button.

我还介绍了enabled在按钮上启动或停止动画的参数。

Finally, if you want you can stop animation after a specific timewith the stopAfterparameter.

最后,如果您愿意,您可以使用stopAfter参数在特定时间后停止动画

Usage:

用法:

yourButton.blink() // infinite blink effect with the default duration of 1 second

yourButton.blink(enabled:false) // stop the animation

yourButton.blink(duration: 2.0) // slowly the animation to 2 seconds

yourButton.blink(stopAfter:5.0) // the animation stops after 5 seconds.

Typical uses:

典型用途:

yourButton.blink(duration: 1.5, stopAfter:10.0)
// your code..
yourButton.blink()
// other code..
yourButton.blink(enabled:false)

回答by Anh Dung dungi Pham

You can try something like this:

你可以尝试这样的事情:

extension UIView {
    func blink() {
        UIView.animateWithDuration(0.5, //Time duration you want,
            delay: 0.0,
            options: [.CurveEaseInOut, .Autoreverse, .Repeat],
            animations: { [weak self] in self?.alpha = 0.0 },
            completion: { [weak self] _ in self?.alpha = 1.0 })
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW,Int64(2 * NSEC_PER_SEC)),dispatch_get_main_queue()){
            [weak self] in
            self?.layer.removeAllAnimations()
        }
    }
}

回答by krish

Swift 3.0

斯威夫特 3.0

func btnFlash_Clicked(sender: AnyObject) {

    if !flashing{
        callButton.alpha = 1.0
        UIView.animate(withDuration: 0.5, delay: 0.0, options: [.allowUserInteraction], animations: {() -> Void in
            callButton.alpha = 0.5
        }, completion: {(finished: Bool) -> Void in
        })

        flashing = true
    }
    else{
        flashing = false
        callButton.alpha = 0.5
        UIView.animate(withDuration: 0.5, delay: 0.0, options: [.allowUserInteraction], animations: {() -> Void in
            callButton.alpha = 1.0
        }, completion: {(finished: Bool) -> Void in
        })
    }
}

回答by alex_lewis

This UIViewextension "blinks" a view and changes the background colour:

UIView扩展“闪烁”视图并更改背景颜色:

/**
 Blinks a view with a given duration and optional color.

 - Parameter duration: The duration of the blink.
 - Parameter color: The color of the blink.
 */
public func blink(withDuration duration: Double = 0.25, color: UIColor? = nil) {

    alpha = 0.2
    UIView.animate(withDuration: duration, delay: 0.0, options: [.curveEaseInOut], animations: {
        self.alpha = 1.0
    })

    guard let newBackgroundColor = color else { return }
    let oldBackgroundColor = backgroundColor

    UIView.animate(withDuration: duration, delay: 0.0, options: [.curveEaseInOut], animations: {
        self.backgroundColor = newBackgroundColor
        self.backgroundColor = oldBackgroundColor
    })

}

You would then use as follows:

然后,您将按如下方式使用:

buttonScan.blink(color: .green)

回答by Diaa SAlAm

//MARK : Usage 

yourButton.flash()

extension UIButton {

    func flash() {

        let flash = CABasicAnimation(keyPath: "opacity")
        flash.duration = 0.5
        flash.fromValue = 1
        flash.toValue = 0.1
        flash.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
        flash.autoreverses = true
        flash.repeatCount = 3

        layer.add(flash, forKey: nil)
    }
}

回答by black_pearl

with UIViewPropertyAnimatorand Swift 5

使用UIViewPropertyAnimatorSwift 5

UIViewPropertyAnimator.runningPropertyAnimator(withDuration: 1, delay: 0, options: [.curveLinear,.repeat], animations: {
       UIView.setAnimationRepeatCount(3000)
       self.buttonScan.alpha = 0.0
 }, completion: {_ in   })

回答by Vitalii

myButton.alpha = 0.7

UIView.animate(withDuration: 0.3,
                      delay: 1.0,
                    options: [UIView.AnimationOptions.curveLinear, UIView.AnimationOptions.repeat, UIView.AnimationOptions.autoreverse],
                 animations: { myButton.alpha = 1.0 },
                 completion: nil)