First, the .text
property of a UILabel
can be nil
, so it is optional.
If you add this to a view controller's viewDidLoad()
:
let label = UILabel()
print(label.text)
label.text = "abc"
print(label.text)
the output in the debug console will be:
nil
Optional("abc")
Next, if you set the text of a label and then set it again, it replaces any existing text:
let label = UILabel()
print(label.text)
label.text = "abc"
print(label.text)
label.text = "1"
print(label.text)
now the output is:
nil
Optional("abc")
Optional("1")
If you want to get rid of the "Optional" part, you need to unwrap the text:
let label = UILabel()
if let s = label.text {
print(s)
}
label.text = "abc"
if let s = label.text {
print(s)
}
label.text = "1"
if let s = label.text {
print(s)
}
output:
abc
1
Note there is no "nil" output... because the first if let...
statement fails, so the print statement does not get executed.
So, if you want your label to show "CUSTOM 1" / "CUSTOM 2" / "CUSTOM 3" / etc, you can either set it that way in cellForRowAt
:
cell.myLabel.text = "CUSTOM (indexPath.row)"
or, you can append the existing text:
// unwrap the optional text
if let s = cell.myLabel.text {
cell.myLabel.text = s + " (indexPath.row)"
}
Note, however, that cells are reused, so you could end up with:
CUSTOM 1 7 15 8 23
Much better to set the full text to what you want it to be, than to try and append something each time the cell is used.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…