Using tags in Swift

15,198

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]!
Share:
15,198
Tommy D
Author by

Tommy D

Updated on June 04, 2022

Comments

  • Tommy D
    Tommy D almost 2 years

    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.

  • nhgrif
    nhgrif almost 9 years
    As an added bonus, now we can for in through these. I don't know about Swift, but in Objective-C a for in would definitely be faster than the original C-style for in the question.
  • Anurag Sharma
    Anurag Sharma about 7 years
    @Sulthan why people use outlets more than tags? I mean it decreases the code length right! Did I sound good or am I increasing the complexity by using tags?
  • Sulthan
    Sulthan about 7 years
    @AnuragSharma Code length is and never has been a relevant metric to anything. What's important is code readability and maintainability. Everytime you use a tag, you have to create a constant. Everytime you want to use a tagged view, you have to search the view hierarchy to find it. What's easier to read? Connecting the view to a named variable or creating an identifier? Use the view directly or search for it before using?
  • Anurag Sharma
    Anurag Sharma about 7 years
    @Sulthan that's very helping, but what if I declare the UIView in the viewWillLayoutSubview() or viewDidLoad() for the first time only!
  • Sulthan
    Sulthan about 7 years
    @AnuragSharma You can still put it into a property. Nothing is changing.
  • Anurag Sharma
    Anurag Sharma about 7 years
    @Sulthan Ok then, if nothing is changing then for sure I opt for the property instead of using the tag. Thanks a lot!