首页 > 解决方案 > IOS/SWIFT How to make the button highlight for a period of time with swift

问题描述

How do I change the button background color when the button is highlighted with swift,then I also want to know . How can I make this background color last for a period of time instead of clicking it to disappear immediately? For example, I want it to disappear 2 seconds after clicking. I checked some information and couldn't find a way. All I can think of is to write a click event, then change the background color of the button and set a time to change it back

标签: iosswift

解决方案


I found the method. As a novice, I can't fully understand it, but it can be used. Friends with similar problems can refer to it

class MyButton : UIButton {
@IBInspectable var normalBackgroundColor: UIColor? {
    didSet {
        backgroundColor = normalBackgroundColor
    }
}

@IBInspectable var highlightedBackgroundColor: UIColor?

override var isHighlighted: Bool {
    didSet {
        if oldValue == false && isHighlighted {
            highlight()
        } else if oldValue == true && !isHighlighted {
            unHighlight()
        }
    }
    
}
func highlight() {
    animateBackground(to: highlightedBackgroundColor, duration: highlightDuration)
}

func unHighlight() {
    animateBackground(to: normalBackgroundColor, duration: highlightDuration)
}
var highlightDuration: TimeInterval = 1

private func animateBackground(to color: UIColor?, duration: TimeInterval) {
    guard let color = color else { return }
    UIView.animate(withDuration: highlightDuration) {
        self.backgroundColor = color
    }
}  }

You can create a new file and write the above code Then bind the button class as shown in the figure

enter image description here

Finally, your button has the content you want in the right property panel enter image description here You can modify the animation time by changing the value of highlightduration


推荐阅读