1 Replies - 2556 Views - Last Post: 21 January 2016 - 11:03 AM

#1 drayarms  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 199
  • Joined: 18-May 11

How to correctly use viewWithTag in swift?

Posted 21 December 2015 - 12:54 AM

I added a series of UIViews programmatically to an application, basically using a for loop. This is how I did it

            for var i=0; i<5; ++i{
               
                //Define an image view
                let myView = UIImageView(frame: CGRectMake(0, 0, CGFloat(30), CGFloat(30) )) 
                
                //Style the view
                myView.backgroundColor=UIColor.greenColor()
                myView.layer.cornerRadius=2
                myView.layer.borderWidth=1
                
  
                
                
                //Define your image
                let myImage = UIImage(named: "someImage.jpg")!
                
   
                //Add image in imageview
                myView.image = myImage;
                
                self.addSubview(myView) //Add the imageview to main view
                

                myView.tag = i//Tag the imageview
                
            }
            
        







Now when I attempt to reference the first imageview with the following code
        let theLabel = UIImageView.viewWithTag(1)
        
        if let theLabel = UIImageView.viewWithTag(1) as? UIImageView{
            //Do something with the imageview
        }



I get this error:

"cannot convert value of type 'int' to expected argument type 'UIView' "

So what am I doing wrong? Isn't the argument supposed to be an int? Or am I using the tag property and associated viewWithTag() method completely wrong? :dozingoff:/> Thanks!!

Is This A Good Question/Topic? 0
  • +

Replies To: How to correctly use viewWithTag in swift?

#2 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon

Reputation: 2965
  • View blog
  • Posts: 11,222
  • Joined: 15-July 08

Re: How to correctly use viewWithTag in swift?

Posted 21 January 2016 - 11:03 AM

Sorry it's been a while; hopefully, you've solved your problem since then. However, my thought is that you're trying to access the viewWithTag function off of the static context. Try self.view.viewWithTag(1) instead.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1