Search code examples
swiftuiimageviewswift3viewwithtag

Change UIView based on viewWithTag in Swift3


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


Solution

  • Simply like this.

    if let findView = self.view.viewWithTag(touchSQ+1) as? UIImageView {
        findView.image = UIImage(named: "bp.png")
    }