【发布时间】:2019-10-29 01:19:49
【问题描述】:
我试图在按下两个按钮之一时更改标签的文本(按钮 1 名为“过去”,按钮 2 名为“未来”)。结果应该是按下按钮 1 或按钮 2 时,它应该使用数组 1 (pastData) 或数组 2 (futureData) 的内容更改标签文本。
我很困,所以我不知道从哪里开始了。
import UIKit
var pastData = [
"What was the greatest achievement you accomplished the past five years?",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
]
var futureData = [
"What is the single most important thing to have accomplished within the next five years?",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
]
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func pastButton(_ sender: UIButton) {
}
@IBAction func futureButton(_ sender: UIButton) {
}
@IBOutlet weak var label: UILabel!
}
我希望按下按钮时,它会使用特定数组中的索引之一更改标签文本。
我相信它与这个线程不同,因为我的线程是关于如何在按下按钮时更改文本,而不是每次显示时: How to randomize UILabel text each time the view controller is showed
【问题讨论】:
-
你如何决定数组中的哪个元素应该显示在标签上?
-
这是一个非常好的问题。我希望这回答了你的问题。当按下 Future 按钮时,我希望它从 futureData 数组中随机选择一个文本,而过去的按钮 / pastData 数组也是如此。
-
就像很多新手对一种语言提出的问题一样,这实际上是 5 个独立的问题。他们之前已经分别回答过,但是新手无法做出所有这些区分。问题是:1)我如何确定变量的范围以便类函数可以看到它们? 2) 如何管理
@IBOutlet命名以避免运行时崩溃? 3) 我如何操作数组,特别是选择一个随机元素 4) 代码在哪里处理用户操作,如按钮按下? 5) 我如何使用我的变量直观地操作像UILabels 这样的简单视图?