It's tricky on this forum as I can't edit a post or comments, but I'll post it again with edits:
VC
func addButtons() {
for (feed,amount) in feedInventory where amount 0 {
let filteredFeedProducts = feedProducts.filter { $0.code.contains(feed)}
for filteredFeed in filteredFeedProducts {
let horizontalStack = UIStackView(frame: .zero)
horizontalStack.axis = .horizontal
horizontalStack.alignment = .firstBaseline
let label = UILabel(frame: .zero)
label.text = "\(filteredFeed.name)"
horizontalStack.addArrangedSubview(label)
let rationAmount = UILabel(frame: .zero)
let rationIndex = Int(rationArrayPosition[filteredFeed.code]!)
rationAmount.text = "\(myHorses[horseIndex].ration[rationIndex])"
horizontalStack.addArrangedSubview(rationAmount)
let stepper = UIStepper(frame: .zero)
stepper.minimumValue = 0
stepper.maximumValue = 900
stepper.wraps = false
stepper.autorepeat = false
stepper.addTarget(self, action: #selector(stepperValueChanged(_:)), for: .valueChanged)
stepper.accessibilityLabel = "\(filteredFeed.code)"
horizontalStack.addArrangedSubview(stepper)
feedStack.addArrangedSubview(horizontalStack)
}}}
func removeButtons() {
let rows = feedStack.arrangedSubviews
.filter {$0 is UIStackView}
for row in rows {
feedStack.removeArrangedSubview(row)
row.removeFromSuperview()
}
}
@objc func stepperValueChanged(_ sender:UIStepper!) {
let rationIndex = rationArrayPosition[sender.accessibilityLabel!]
myHorses[horseIndex].ration[rationIndex ?? 00] += Int(sender.value)
print(myHorses[horseIndex].ration[rationIndex ?? 00])
removeButtons()
addButtons()
}
Model
var feedInventory: [ String : Int ] = [
"oats" : 0,
"soyPellets" : 20]
var feedProducts = [
FeedProduct(name: "Oats", code: "oats"),
FeedProduct(name: "Soy Pellets", code: "soyPellets")]
var rationArrayPosition: [ String : Int ] = [
"oats" : 0,
"soyPellets" : 1]
struct Horse {
var name : String!
var ration : [Int]
}
var horseIndex = 0
var myHorses = [
Horse(name: "Donnerhall", ration: [2,0]),
Horse(name: "Celeste", ration: [3,1])]
@IBOutlet weak var feedStack: UIStackView!
struct FeedProduct {
var name : String
var code : String
}