Using tags in Swift

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

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

Failed to pass value of type '_UISizeTrackingView' (0x18a023c) to 'UIButton' (0x1899298). (lldb)

For the loop:

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

I narrowed it down to a problem with an element using the 0 tag. I looked through all the elements in my View Controller panel and see no conflicts. I see only one button using tag = 0.

I even compiled it, replacing the β€œi” in the loop with β€œ0” and getting the same problem. When I replaced it with β€œ1” or β€œ2”, it works fine with this single image.

How to find out which object uses tag 0? I clicked on all of them (including the main "View"), but it seems that I did not find anything.

+5
source share
2 answers

As @ranunez has already said, the default tag is 0. I disagree with the advice on using non-zero tags.

My advice: do not use tags at all. If you want to use the view in code, declare it a power outlet and plug it in. If you want to iterate over several views, create an array from your points or use a collection of points:

 @IBOutlet var buttons: [UIButton]! 
+9
source

By default, views have a tag of 0, so you should not count on this to remove your objects with a tag of 0. Try to give your buttons a different set of tags, for example: 1000, 1001, 1002, etc. instead

+1
source

All Articles