這是代碼,它給了我一個錯誤,
let coffee = sender.currentTitle!這是我的問題。
我試圖讓我的按鈕成為 Decaf 按鈕的名稱,但是當我按下它時,它給了我那個錯誤。
import UIKit
import AVFoundation
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBOutlet weak var progressBar: UIProgressView!
@IBOutlet weak var titleLabel: UILabel!
let coffeeTimes = ["Decaf": 5, "coffee": 5]
var timer = Timer()
var player: AVAudioPlayer!
var totalTime = 0
var secondsPassed = 0
@IBAction func coffeeSelected(_ sender: UIButton) {
timer.invalidate()
let coffee = sender.currentTitle! //1.This is the line were its giving me the Error"
totalTime = coffeeTimes[coffee]!
progressBar.progress = 0.0
secondsPassed = 0
titleLabel.text = coffee
timer = Timer.scheduledTimer(timeInterval: 1.0, target:self, selector: #selector(updateTimer), userInfo:nil, repeats: true)
}
@objc func updateTimer() {
if secondsPassed < totalTime {
secondsPassed = 1
progressBar.progress = Float(secondsPassed) / Float(totalTime)
print(Float(secondsPassed) / Float(totalTime))
} else {
timer.invalidate()
titleLabel.text = "check coffee"
let url = Bundle.main.url(forResource: "alarm_sound", withExtension: "mp3")
player = try! AVAudioPlayer(contentsOf: url!)
player.play()
}
}
}
uj5u.com熱心網友回復:
使用可選系結,這樣應用程式就不會崩潰。這個 if let 陳述句只會在“currentTitle”實際存在時運行,在你的情況下,它不存在,所以你的代碼中一定有其他問題。
if let coffee = sender.currentTitle {
totalTime = coffeeTimes[coffee]
titleLabel.text = coffee
progressBar.progress = 0.0
secondsPassed = 0
}
如果值不存在,另一種方法是從整個函式回傳。不要同時使用兩者。
guard let coffee = sender.currentTitle else { return }
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/400495.html
上一篇:當我運行我的應用程式并按下一個按鈕時,按鈕標題與應用程式的主標題相結合,看起來很混亂,我該如何修復它
下一篇:如何從屬性陣列創建串列中的部分?
