当多次按下按钮时,将相同的文本添加到标签
问题描述:
我想在按下按钮时将文本附加到标签。当再次按下按钮时,我希望将相同的文本添加到标签中的新行中。当多次按下按钮时,将相同的文本添加到标签
var someText = "text"
@IBAction func button1(_ sender: UIButton) {
label.text = someText
}
当我这样做时,标签只打印: 文本。
如果按钮被按下3次,我想在标签打印:“文字” - 新线 - “文字” - 新线 - “文本”
或者。
3x文字
我应该如何去做到这一点?
答
正如马特所说,你需要使用编程。只需取出标签中的字符串,然后在新文本中添加一行即可。我没有测试这个代码,但它会是这样的:
// variable for the "text"
var someText = "text"
@IBAction func button1(_ sender: UIButton) {
// if the label text is empty, do not append a new line character
if label.text?.isEmpty {
label.text = someText
} else {
// if the label contains text, append a new line character and add the new text
label.text += "\n" + someText
}
}