Reputation: 355
In Objective C it was easy to change the image of a UIView
based on a tag using a cast to (UIImageView*)
— something like:
[ (UIImageView*) [self.view viewWithTag:n+1] setImage:[UIImage imageNamed:@"bb.png"]];
I've been trying to find an up-to-date example that would do the same thing in Swift 3. I finally came on the solution — you need to use the as! keyword and optionally cast to UIImageView?
. if you need to do this — here's some working code:
// SWIFT3 change UIView based on viewWithTag (johnrpenner, toronto)
override func viewDidLoad()
{
super.viewDidLoad()
var n : Int = 0
for i in stride(from:7, to:-1, by:-1) {
for j in 0...7 {
n = i*8+j
let sqImageView = UIImageView(image: UIImage(named: "wp.png"))
sqImageView.tag = n+1
sqImageView.frame.origin.x = (CGFloat(j) * cellX + xStartAdj)
sqImageView.frame.origin.y = ( (CGFloat(7-i) * cellY) + yStartAdj )
view.addSubview(sqImageView)
}
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
//func touchesBegan(touches: Set<UITouch>, with event: UIEvent?)
{
if let touch = touches.first {
let touchPos = touch.location(in: self.view) //swift3
let touchSQ : Int = coordToSQ(touchPoint:touchPos)
// change UIView.image based on viewWithTag
if var findView : UIImageView = view.viewWithTag(touchSQ+1) as! UIImageView? { findView.image = UIImage(named: "bp.png")! }
}
}
Any how — it took a couple hours to figure this out, and everything out there is for Swift 2 or Objective C — thought a Swift 3 example might be useful.
cheers! john p
Upvotes: 3
Views: 1273
Reputation: 355
thx nirav — using let .. as? UIImageView .. is the good answer.
this might be a useful function:
func setImageView(byTag:Int, toImageNamed:String)
{
if let findView = self.view.viewWithTag(byTag) as? UIImageView {findView.image = UIImage(named: toImageNamed)}
return
}
Upvotes: 0
Reputation: 72410
Simply like this.
if let findView = self.view.viewWithTag(touchSQ+1) as? UIImageView {
findView.image = UIImage(named: "bp.png")
}
Upvotes: 2