我只是一個 swift 的初學者。
我有下面的代碼,我試圖能夠重構它,看起來下面的代碼不是很干凈。
希望能得到你的幫助
class ViewController: UIViewController {
@IBOutlet private weak var titleButton: UIButton!
@IBOutlet private weak var titleLabel: UILabel!
let nameData = [Data(name: "A"), Data(name: "B"), Data(name: "C"), Data(name: "D")]
override func viewDidLoad() {
super.viewDidLoad()
setupTitle()
}
func setupTitle() {
let title = nameData.randomElement()?.name
if title == "A" {
titleLabel.text = "AND"
titleButton.backgroundColor = UIColor.black
} else if title == "B" {
titleLabel.text = "BOY"
titleButton.backgroundColor = UIColor.red
} else if title == "C" {
titleLabel.text = "COCO"
titleButton.backgroundColor = UIColor.blue
} else if title == "D" {
titleLabel.text = "DADDY"
titleButton.backgroundColor = UIColor.gray
}
}
}
uj5u.com熱心網友回復:
試試開關:
class ViewController: UIViewController {
@IBOutlet private weak var titleButton: UIButton!
@IBOutlet private weak var titleLabel: UILabel!
let nameData = [Data(name: "A"), Data(name: "B"), Data(name: "C"), Data(name: "D")]
override func viewDidLoad() {
super.viewDidLoad()
setupTitle()
}
func setupTitle() {
guard let title = nameData.randomElement()?.name else { return}
switch title {
case "A":
titleLabel.text = "AND"
titleButton.backgroundColor = .black
case "B":
titleLabel.text = "BOY"
titleButton.backgroundColor = .red
case "C":
titleLabel.text = "COCO"
titleButton.backgroundColor = .blue
case "D":
titleLabel.text = "DADDY"
titleButton.backgroundColor = .gray
}
}
}
uj5u.com熱心網友回復:
由于資料是靜態的,我的建議是將值放入結構title
中color
struct NameData {
let name, title: String
let color: UIColor
}
class ViewController: UIViewController {
@IBOutlet private weak var titleButton: UIButton!
@IBOutlet private weak var titleLabel: UILabel!
let nameData = [NameData(name: "A", title: "AND", color: .black),
NameData(name: "B", title: "BOY", color: .red),
NameData(name: "C", title: "COCO", color: .blue),
NameData(name: "D", title: "DADDY", color: .gray)]
override func viewDidLoad() {
super.viewDidLoad()
setupTitle()
}
func setupTitle() {
let item = nameData.randomElement()!
titleLabel.text = item.title
titleButton.backgroundColor = item.color
}
}
該name
物業未使用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/507551.html
上一篇:使用未知鍵快速解碼JSON
下一篇:如何以間隔從SFSafariViewController中的UITextField打開用戶的URL鏈接(任何鏈接)?/斯威夫特5