[英]Swift 4: How can I add a Countdown timer inside of my UIbutton .settitle?
I am trying to add a Countdown timer inside of my UIButton in the .settitle.我正在尝试在 .settitle 中的 UIButton 内添加一个倒计时计时器。 How can I do this?
我怎样才能做到这一点? The image below is what I am trying to accomplish.
下面的图片是我想要完成的。
Then once the timer gets to 0, I want the background color to change to a different color.然后一旦计时器变为 0,我希望背景颜色更改为不同的颜色。
Here is the code I have so far.这是我到目前为止的代码。
let sendSMSAgainNumberOfTime: UIButton = {
let button = UIButton(type: .system)
button.backgroundColor = .black
button.layer.cornerRadius = 7
button.setTitle("SEND SMS AGAIN IN 36", for: .normal)
button.setTitleColor(.white, for: .normal)
button.titleLabel?.font = UIFont(name: "open sans", size: 16)
return button
}()
You can try a timer你可以试试定时器
var countTimer:Timer!
var counter = 36
// //
in viewDidLoad
set it在
viewDidLoad
设置它
self.countTimer = Timer.scheduledTimer(timeInterval: 1 ,
target: self,
selector: #selector(self.changeTitle),
userInfo: nil,
repeats: true)
func changeTitle()
{
if counter != 0
{
button.setTitle("SEND SMS AGAIN IN \(counter)", for: .normal)
counter -= 1
}
else
{
countTimer.invalidate()
button.backgroundColor = // set any color
}
}
// //
OR use IOS 10+ timer block或使用 IOS 10+ 计时器块
// //
let sendSMSAgainNumberOfTime: UIButton = {
let button = UIButton(type: .system)
button.backgroundColor = .black
button.layer.cornerRadius = 7
button.setTitle("SEND SMS AGAIN IN 36", for: .normal)
button.setTitleColor(.white, for: .normal)
button.titleLabel?.font = UIFont(name: "open sans", size: 16)
// timer block exists from ios 10 +
if #available(iOS 10.0, *) {
Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (t) in
if(button.tag != 37)
{
button.setTitle("SEND SMS AGAIN IN \(36-button.tag)", for: .normal)
button.tag += 1
}
else
{
t.invalidate()
button.backgroundColor = // set any color
}
})
} else {
// Fallback on earlier versions
}
return button
}()
You can also do the following in Swift 5. This is a very simple countdown that prints each second remaining after button is tapped.您还可以在 Swift 5 中执行以下操作。这是一个非常简单的倒计时,用于打印点击按钮后剩余的每一秒。 Let me know if you have any questions (:
如果您有任何问题,请告诉我(:
class ViewController: UIViewController {
var secondsRemaining = 30
@IBAction func startTimer(_ sender: UIButton) {
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (Timer) in
if self.secondsRemaining > 0 {
print ("\(self.secondsRemaining) seconds")
self.secondsRemaining -= 1
} else {
self.invalidate()
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.