Reputation: 177
I am trying to add a Countdown timer inside of my UIButton in the .settitle. 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.
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
}()
Upvotes: 4
Views: 15630
Reputation: 155
You can also do the following in Swift 5. This is a very simple countdown that prints each second remaining after button is tapped. 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()
}
}
}
Upvotes: 7
Reputation: 100503
You can try a timer
var countTimer:Timer!
var counter = 36
//
in viewDidLoad
set it
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
//
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
}()
Upvotes: 13