Tommy D
Tommy D

Reputation: 53

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.

Upvotes: 5

Views: 16514

Answers (2)

Sulthan
Sulthan

Reputation: 130082

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]!

Upvotes: 9

ranunez
ranunez

Reputation: 348

By default, views have a tag of 0, so you shouldn't count on this to remove your objects with a tag of 0. Try giving your buttons a different set of tags, ex: 1000, 1001, 1002, etc instead

Upvotes: 0

Related Questions