Search code examples
swiftviewwillappearviewwithtag

unable to find view with tag


In my viewWillAppear() I create a label and give it a tag. When another condition is met, I try to remove the label, but for some reason, that is not working and the label is still in the view. I must be doing something wrong...

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    var label: UILabel?

    // Add label if there are no recipes
    if (recipeBook.recipesArr.count == 0) {

        label = self.view.viewWithTag(123) as? UILabel
        //label?.tag = 123 // arbitrary num

        label = UILabel(frame: CGRect(x: 0, y: self.view.frame.height/3, width: self.view.frame.width, height: 100))
        label?.text = "Add A Recipe"
        label?.textColor = UIColor(red:0.93, green:0.92, blue:0.92, alpha:1.0)
        label?.font = label?.font.withSize(36)
        label?.textAlignment = .center

        self.view.addSubview(label!)
    }

    else {

        // remove it
        if let foundLabel = self.view.viewWithTag(123) {
            foundLabel.removeFromSuperview()
        } else {
            print("Couldn't find label with tag in view")
        }

    }

}

I didn't realize in this line label = UILabel(frame: CGRect(x: 0, y: self.view.frame.height/3, width: self.view.frame.width, height: 100)) I was creating a new label which has a default tag of 0. Changed it to label?.frame = CGRect(x: 0, y: self.view.frame.height/3, width: self.view.frame.width, height: 100) so that I'm not creating a new label and everything is working fine. Silly mistake.


Solution

  • Your code is not doing what you think it is. If your recipesArr is empty (or more accurately the count is zero) you are trying to find a label/view with the tag 123. That is then ignored and you create a new label but don't give it a tag.

    What you need to do is assign the label you create the tag 123 after you create it like this:

    label?.tag = 123
    

    Then you will have created the label and set it's tag so it can then subsequently be found.