ios - 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
解决方案
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
Finally, your button has the content you want in the right property panel You can modify the animation time by changing the value of highlightduration
推荐阅读
- xampp - 在 Windows Server 2012 64 位上安装 XAMPP 32 位
- angular - 为什么原始形式总是在角度有效
- c++ - 概念评估能否取决于评估的位置?
- drupal - Drupal 8.6 无法主题化视图
- sql - 选择查询 0=0 Vs 不存在
- html - 如何在 HTML 中使用 HTML 实体代码而不是字符
- kubernetes - 将 aksapp.io 分配给有效的 DNS 名称
- ruby-on-rails - Rails 5.2.1 的 RailsApps mysql2 gem 版本错误
- qnamaker - 未生成 Azure QnaMaker 聊天日志
- python - ReLU 可以代替神经网络中的 Sigmoid 激活函数吗