Swift 寫九九乘法表

twber
彼得潘的 Swift iOS / Flutter App 開發教室
6 min readSep 22, 2020
  1. Nested for-loop 產生 100個 UILabel:

筆記: view.addSubview(label) 要寫在 inner loop

let width = view.frame.width / 10
var x: CGFloat = 0
for i in 0...9{
print(x)
var y: CGFloat = width
for j in 0...9{
let label = UILabel(frame: CGRect(x: x, y: y, width: width, height: width))
if i == 0, j == 0 {
label.text = "X"
label.font = UIFont.boldSystemFont(ofSize: 17)
}else if i != 0, j == 0 {
label.text = "\(i)"
label.font = UIFont.boldSystemFont(ofSize: 17)
}else if i == 0, j != 0 {
label.text = "\(j)"
label.font = UIFont.boldSystemFont(ofSize: 17)
}else if j == 9 || (i>1 && i<5 && i+j == 10) || (j >= 5 && i == j) {
label.text = "\(j*i)"
label.backgroundColor = UIColor(
red: .random(in: 0...1),
green: .random(in: 0...1),
blue: .random(in: 0...1),
alpha: 1.0
)
}else{
label.text = "\(j*i)"
}
view.addSubview(label)
y = y + width*CGFloat(1)
}
x = x + width
}

參考作品:

2. Nested for-loop 寫入String:

for i in 1...9{
for j in 1...9{
if i == 9 || (j > 1 && j<5 && i+j == 10) || (i >= 5 && i == j) {
content += " " + "\(i*j)" + ""
content += "\t"
}else{
content += " " + "🍎" + ""
content += "\t"
}
}
content += "\n"
}
numberLabel.text = content
numberLabel.textAlignment = .center

}

由于只有一个Label, NSAttributedString 無法成功更換 String 裡以 if … esle 區隔的 backgroundColor。彼得潘提醒前一種作法方便更換個別 label 的backgroundColor 和 font。

因此,要将content 定義為NSMutableAttributedString屬性,同時創建string 。以for-loop 將一段段的string藉由append()拼接起來,最後放到content 裡。如此能以if vs else 分別設定不同的string 內容和attributes(String 的樣式)。完整思路和作法寫在下面文章中。

numberLabel.textAlignment = .center
var content: NSMutableAttributedString = NSMutableAttributedString()
for i in 1...9{
for j in 1...9{
let string: String
let attributes: [NSMutableAttributedString.Key: Any]
if i == 9 || (j > 1 && j<5 && i+j == 10) || (i >= 5 && i == j) {
string = " \(i*j)\t"
attributes = [
.foregroundColor: UIColor.black,
.backgroundColor: UIColor(
red: .random(in: 0...1),
green: .random(in: 0...1),
blue: .random(in: 0...1),
alpha: 1.0
),
.font: UIFont.boldSystemFont(ofSize: 17)
]
}else{
string = " \(i*j)\t"
attributes = [
//.kern: 5,
.foregroundColor: UIColor.black,
.backgroundColor: UIColor.white,
.font: UIFont.boldSystemFont(ofSize: 17)
]
}
let attributedStringToAppend = NSMutableAttributedString(string: string, attributes: attributes)
content.append(attributedStringToAppend)
}
content.append(NSAttributedString(string: "\n"))
}
numberLabel.attributedText = content
}

--

--