我有这个带有文本和名称的JSON文件:0.json:
public int getItemPosition(Object object) {
return POSITION_NONE;
}
我从此文件中打印{
"questions" : [{"text1": "1", "text2": "1"},
{"text1": "2", "text2": "2"},
{"text1": "3", "text2": "3"}]
}
并将其显示在标签
我的代码:
text1, text2
当应用开始时,我想要显示第一行struct Root : Decodable {
let questions : [Question]
}
struct Question : Decodable {
let text1, text2 : String
}
override func viewDidLoad() {
super.viewDidLoad()
let url = Bundle.main.url(forResource: "0", withExtension: "json")!
do {
let data = try! Data(contentsOf: url)
let result = try JSONDecoder().decode(Root.self, from: data)
for question in result.questions {
label2.text = "\(question.text2)"
label1.text = "\(question.text1)"
}
} catch {
print("error: ", error)
}
}
,如果用户点击按钮,我想显示第二行"text1": "1", "text2": "1"
,点击按钮后,我想显示第三行"text1": "2", "text2": "2"
和等怎么办?
更新 代码:
"text1": "3", "text2": "3"
答案 0 :(得分:1)
为问题和计数器创建属性
var questions = [Question]()
var counter = 0
viewDidLoad
填充questions
中
override func viewDidLoad() {
super.viewDidLoad()
let url = Bundle.main.url(forResource: "0", withExtension: "json")!
let data = try! Data(contentsOf: url)
let result = try! JSONDecoder().decode(Root.self, from: data)
self.questions = result.questions
}
创建IBAction
。在正文中获取当前counter
值的问题,将文本值分配给标签并递增计数器。如果计数器超过questions
中的项目数,则将计数器重置为0(由%
运算符方便地执行)。将操作连接到Interface Builder
@IBAction func push(_ sender : UIButton)
{
let question = questions[counter]
label2.text = question.text2 // no String Interpolation
label1.text = question.text1
counter = (counter + 1) % questions.count
}