You can set the green / red tint color easily by using the progress
value you've already calculated:
let progress = Float(UserDefaults.standard.double(forKey: "spentThisMonth") / UserDefaults.standard.double(forKey: "monthlyExpenseLimit"))
// progress is now a value between 0.0 and 1.0
progressView.progress = progress
let red = CGFloat(progress)
let green = CGFloat(1.0 - progress)
progressView.progressTintColor = UIColor(red: red, green: green, blue: 0.0, alpha: 1.0)
Here's a working example - each time you tap the screen, the progress will increment until it reaches 100%, at which time it will decrement back to Zero:
class ProgressTintViewController: UIViewController {
let progressView = UIProgressView()
let statsLabel = UILabel()
var spentThisMonth: Float = 0
var monthlyExpenseLimit: Float = 100
var isAdding: Bool = true
override func viewDidLoad() {
super.viewDidLoad()
progressView.translatesAutoresizingMaskIntoConstraints = false
statsLabel.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(progressView)
view.addSubview(statsLabel)
let g = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
progressView.topAnchor.constraint(equalTo: g.topAnchor, constant: 80.0),
progressView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
progressView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
statsLabel.topAnchor.constraint(equalTo: progressView.bottomAnchor, constant: 20.0),
statsLabel.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
statsLabel.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
])
statsLabel.numberOfLines = 0
let t = UITapGestureRecognizer(target: self, action: #selector(self.tapped))
view.addGestureRecognizer(t)
updateProgress()
}
@objc func tapped() -> Void {
if isAdding {
spentThisMonth += 10
} else {
spentThisMonth -= 10
}
updateProgress()
if spentThisMonth >= monthlyExpenseLimit {
spentThisMonth = monthlyExpenseLimit
isAdding = false
}
if spentThisMonth <= 0 {
spentThisMonth = 0
isAdding = true
}
}
func updateProgress() -> Void {
//let progress = Float(UserDefaults.standard.double(forKey: "spentThisMonth") / UserDefaults.standard.double(forKey: "monthlyExpenseLimit"))
// progress is now a value between 0.0 and 1.0
let progress = spentThisMonth / monthlyExpenseLimit
progressView.progress = progress
let red = CGFloat(progress)
let green = CGFloat(1.0 - progress)
progressView.progressTintColor = UIColor(red: red, green: green, blue: 0.0, alpha: 1.0)
var str = ""
str += "Tap to change progress"
str += "
"
str += "Spent This Month: (spentThisMonth)"
str += "
"
str += "Monthly Limit: (monthlyExpenseLimit)"
str += "
"
str += "Percent: (progress)"
statsLabel.text = str
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…