Итак, я извлекаю данные из Firebase и затем помещаю эти данные в виде строки в заголовок кнопок. Тем не менее, название кнопок не меняется по некоторым причинам.
По сути, он помещает данные в кнопку на основе ее тега. Я устанавливаю тег для каждой кнопки в коде.
Файл Json из базы данных:
{
"mix-questions" : [ {
"1" : "Eu Ro Wang",
"2" : "Keerti Soundappan",
"3" : "Galadriel Coury",
"answer" : "Madelyn Koch",
"question" : "Which one is not a national officer?"
}, {
"1" : "pure risk may deprive society of certain goods or services determined to bear excessive risk",
"2" : "pure risk can result in feelings of mental unrest and worry that can drain human energies",
"3" : "reserve funds may be necessitated that may not yield the highest rate of return available",
"answer" : "pure risk results in gambling, which is a destructive social force",
"question" : "Pure risk may be said to create an economic burden in all except which one of the following ways?"
}, {
"1" : "property risk",
"2" : "insurance",
"3" : "personal risk",
"answer" : "liability risk",
"question" : "The risk of potential losses to others as a result of injury or damage you may have caused is:"
}, {
"1" : "dishonest employee",
"2" : "building fire, oily rags, and a dishonest employee",
"3" : "oily rags and a gas leak",
"answer" : "a building fire",
"question" : "Examples of physical hazards include:"
}, {
"1" : "the car that Ken hit was a total loss",
"2" : "Ken's car sustained $5,000 in damages",
"3" : "Ken incurred $5,000 in medical expenses",
"answer" : "the driver of the other car suffered $30,000 in bodily injuries",
"question" : "Ken fell asleep while driving late at night. He crossed the center line and hit a car approaching from the other direction. The following losses occurred:"
}, {
"1" : "injuries to another person arising out of the insured's negligent operation of a vehicle",
"2" : "medical payments resulting from the transmission of a communicable disease",
"3" : "workers compensation medical payments",
"answer" : "injury to a resident employee at the insured's home",
"question" : "Which one of the following losses would be covered under the medical payments coverage of the Homeowners 3 policy?"
}, {
"1" : "partial disability",
"2" : "temporary disability",
"3" : "total disability",
"answer" : "presumptive disability",
"question" : "A provision in disability insurance that specifies the conditions under which the insured is automatically considered disabled is:"
}, {
"1" : "Peril",
"2" : "Hazard",
"3" : "Risk",
"answer" : "Probability",
"question" : "__________ is the likelihood that an event will occur."
}, {
"1" : "personal contracts",
"2" : "contracts of adhesion",
"3" : "aleatory contracts",
"answer" : "unilateral contracts",
"question" : " Kathy entered into an insurance contract with XYZ Insurance Company. When the agent who sold the coverage witnessed Kathy doing something that violated the terms of the contract, he threatened to sue her to make her comply with terms of the contract. Which distinct legal characteristic of insurance contracts states that only the insurer's promise to perform is legally enforceable?"
}, {
"1" : "agent",
"2" : "claims adjustor",
"3" : "risk manager",
"answer" : "appraiser",
"question" : "In what career would a person assess the cost of replacing or repairing damaged property?"
}, {
"1" : "actuary",
"2" : "claims adjustor",
"3" : "loss control engineer",
"answer" : "underwriter",
"question " : "Jan is employed by an insurance company. She reviews applications to determine whether her company should insure the applicant. If insurable, Jan assigns the applicant to a rating category based on the applicant's degree of risk. Jan is a(n):"
} ],
"users" : {
"0vFQYnfIbahHdC1RsuNMW45HYNR2" : {
"email" : "andyjiang55@yahoo.com",
"username" : "itsandyjiang"
},
"Cs7sW01kSEYHYZmBISvjYc1QmDy1" : {
"email" : "test@gmail.com",
"games-played" : 0,
"username" : "test"
},
"GypKikOJbfOPV4m43mQTnLMWBYG3" : {
"email" : "andyjiang@yahoo.com",
"username" : "andyjiang"
},
"Khf6jRX7uuZs40x8w7zapziCsr73" : {
"email" : "andyjiang57@yahoo.com",
"username" : "itsandyjiang3"
},
"OAa5bbNc65acxmr6mauyIQ6bqHb2" : {
"email" : "andyjiang56@yahoo.com",
"username" : "itsandyjiang2"
},
"R86YQRMSxGOIJFC0C6iPDQCgP0W2" : {
"email" : "admin@gmail.com",
"games-played" : "0",
"username" : "admin"
},
"YxxBBxS2WkWtrY8PnLx4jfDqV3o2" : {
"email" : "andyjiang1@yahoo.com",
"username" : "itsandyjiang5"
},
"taikB5Gp1kaAmuPpiHxPoiKmjf03" : {
"email" : "andyjiang2@yahoo.com",
"username" : "itsandyjiang9"
}
}
}
Настройка тегов:
func setup() {
oneAnswerButton.tag = 1
twoAnswerButton.tag = 2
threeAnswerButton.tag = 3
fourAnswerButton.tag = 4
}
Получение данных и присвоение заголовку кнопок:
rightAnswerPlacement = arc4random_uniform(4) + 1//From 0 to n-1 (0-3)+1 = (1-4)
if (questionsArray.isEmpty == true) {
questionNotAsked = true
selectQuestion = arc4random_uniform(10)
}
while(!questionNotAsked) {
selectQuestion = arc4random_uniform(10) //0-9
for questions in self.questionsArray {
if selectQuestion == questions {
self.questionNotAsked = false
break
} else {
self.questionNotAsked = true
}
}
}
questionsArray.append(selectQuestion)
questionNotAsked = false
let ref = Database.database().reference(fromURL: "https://testtest.firebaseio.com/")
ref.child("mix-questions").child(String(selectQuestion)).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
let questionChoosen = value?["question"] as? String ?? ""
let answer = value?["answer"] as? String ?? ""
var button:UIButton = UIButton()
self.questionLabel.text = questionChoosen
var x = 1
let chooses = value?[String(x)] as? String ?? ""
for i in 1...4 {
button = self.view.viewWithTag(i) as! UIButton
if i == Int(self.rightAnswerPlacement) {
button.setTitle(answer, for: .normal)
} else {
button.setTitle(chooses, for: .normal)
x += 1
}
}
// ...
}) { (error) in
print(error.localizedDescription)
}