I am trying to change an image on button click i am using didset to do so where when a variable changes so does the image butt it isn't working even though the variables are changing, here is my code:
the variable too change:
var page:Int=1 {
didSet {
DispatchQueue.main.async { [self] in
let newW = page == 1 ? 0.04*Double(Float(bounds.size.width)) : 0.12*Double(Float(bounds.size.width))
let newX=CGFloat(Float(Int(Float(Double(bounds.size.width)*0.5-newW*0.5))))
currOption = UIImageView(image:UIImage(named: options[page-1].imagePath))
currOption.frame = CGRect(x: newX, y: CGFloat(Int(Float(bounds.size.height/22))), width: CGFloat(newW), height: CGFloat(globW))
}
print("2nd Triggered", currOption)
}
}
the affected variable:
var currOption:UIImageView! = UIImageView(image:UIImage(named: "art.scnassets/A.png"))
where the asset string i:
var options:[AButtons]=[
AButtons(imagePath: "art.scnassets/A.png", name: "A"),
AButtons(imagePath: "art.scnassets/B.png", name: "B"),
AButtons(imagePath: "art.scnassets/C.png", name: "C"),
AButtons(imagePath: "art.scnassets/D.png", name: "D"),
AButtons(imagePath: "art.scnassets/E.png", name: "E"),
]
the function that triggers page to change:
@objc func optionClicked(sender: UIButton){
page = sender.tag + 1
print("1st Trigger",page, sender.tag)
}
all the options objects have a tag thanks all for your time
At some point (although you don't show it in your example), currOption
is added to the view hierarchy. By replacing the variable's value (ie currOption = ...
), although you replace what's stored incurrOption
, you don't replace what is stored in the view hierarchy itself.
Trying replacing your currOption = ...
line with:
currOption.image = UIImage(named: options[page-1].imagePath)
This is, of course, assuming that everything else is working.