Please print (at line 117) the array of horses after the first and second addition. And post the result.
When I add the code "print(myHorses)" and run the IBAction, the console opens but there's nothing in it. Maybe the array is too long?
2. Show the code where you populate the array
The array is populated with the buyHorseButton. There are a couple of sample horses in there already for testing purposes
3. Answer the other questions: What is exactly the problem:
- same horse created several times (does not seem the case) - this is what happens, unless I add cash to the name. Maybe the problem will go away if I assign an ID number to each horse so that they have unique names? I was meaning to do this anyway. I'm not sure why it happens but the randomisation worked with cash added to the name, but not without.
- they do not show randomly as you want in the table ? - the first horse is random, then the following horses are the same as the first one. When I close the simulator and run again, a new random horse is generated and then the following horses are clones of the first.
4. We do not see where you declared myHorses. Please show.
The list of horses are shown in their own VC (shown below), and when a horse is clicked this opens a new VC with fields that fetch data from the myHorses array
import UIKit
class HerdViewController: UIViewController {
@IBOutlet weak var buttonsStack: UIStackView!
override func viewDidLoad() {
super.viewDidLoad()
for horse in myHorses {
let button = UIButton()
button.addTarget(self, action: #selector(self.lookupHorse(sender:)), for: .touchUpInside)
button.setTitleColor(.white, for: UIControl.State.normal)
button.setTitle(horse.name, for: UIControl.State.normal)
button.backgroundColor = colorLiteral(red: 0.005273803137, green: 0.4785152674, blue: 0.3960535526, alpha: 1)
buttonsStack.addArrangedSubview(button)
}
buttonsStack.translatesAutoresizingMaskIntoConstraints = false
}
private var horseSelected: Horse?
@objc func lookupHorse(sender: UIButton){
let horseName = sender.title(for: .normal)
//`lookupHorse` from `myHorses`
if let theHorse = myHorses.first(where: {$0.name == horseName}) {
horseSelected = theHorse
self.performSegue(withIdentifier: "horseViewerSegue", sender: self)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segue.identifier {
case "horseViewerSegue":
let horseVC = segue.destination as! HorseViewController
horseVC.horsePassed = horseSelected
default:
print("Unknown segue: \(segue.identifier ?? "nil")")
}
}
Do you have tips on how to create ID numbers for each new horse created? I have a feeling this can solve the issue. I'll add an ID number property to the buyHorseButton and assign some numbers to the sample horses
Topic:
Programming Languages
SubTopic:
Swift
Tags: