Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using tags in Swift

I have about 15 UIButtons in my controller. Im trying to clear 10 of them with a simple for loop and looks like I am getting some kind of conflict.

When I hit the button to clear, I get the following error:

Could not cast value of type '_UISizeTrackingView' (0x18a023c) to 'UIButton' (0x1899298). (lldb)

For loop is :

for var i = 0; i < 9; i++ {
    button = view.viewWithTag(i) as! UIButton
    button.setImage(nil, forState: .Normal)
}

I have narrowed it down to an issue with an item that is using tag 0. I have looked at all the items on my View Controller Scene and can not seem to find any conflicts. I only see the one button using tag = 0.

I even confrimed it by replacing the 'i' in the loop with '0' and got the same issue. When I replaced it with a '1' or a '2', works fine with that single image.

Any way to see what object is using the tag 0? I have clicked on them all ( including the main 'View') but cant seem to find anything.

like image 283
Tommy D Avatar asked Jun 19 '15 23:06

Tommy D


1 Answers

As there was already said by @ranunez, the default tag is 0. I don't agree with the advice to use non-zero tags.

My advice is, don't use tags at all. If you want to use a view in code, declare an outlet for it and connect it. If you want to iterate over several views, create an array from your outlets or use a collection of outlets:

@IBOutlet var buttons: [UIButton]!
like image 185
Sulthan Avatar answered Oct 05 '22 20:10

Sulthan