我正在尝试在.settitle中添加我的UIButton内的倒数计时器。我怎样才能做到这一点?下面的图片是我想要完成的。
然后一旦计时器变为0,我希望背景颜色变为不同的颜色。
这是我到目前为止的代码。
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
}()
答案 0 :(得分:5)
你可以尝试一个计时器
var countTimer:Timer!
var counter = 36
//
在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
}
}
//
或使用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
}()
答案 1 :(得分:3)
您还可以在Swift 5中执行以下操作。这是一个非常简单的倒计时,在点击按钮后,会每秒显示剩余的秒数。让我知道您是否有任何疑问(:
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()
}
}
}