0ndre_
0ndre_

Reputation: 3631

Can't remove UILabel from it's superview

I am facing a problem. I have a class which adds UILabel to some other view.

That's the class:

    class noDataColor{

        let errLabel = UILabel()

        func addNoDataLabel(_ tableView:UITableView, text:String, color: UIColor){

        //Err label

        self.errLabel.frame = CGRect(x: 15, y: 20, width: tableView.bounds.width, height: 60)
        self.errLabel.textColor = color
        self.errLabel.text = text
        self.errLabel.isHidden = false
        tableView.addSubview(self.errLabel)
        print("errLabelFrame\(errLabel.frame)") //Prints normal frame
}

    func removeNoDataLabelColor(){
        //Err label
            print("Executed")
            errLabel.isHidden = true
            errLabel.removeFromSuperview()
            errLabel.textColor = UIColor.clear
            print("errLabelFrame\(errLabel.frame)") //Prints (0.0,0.0,0.0,0.0)
        }
    }

And then I add my errLabel using this line (everything works fine and my label is added):

noDataColor().addNoDataLabel(self.tableView, text: errorMessage!, color: .white)

But here comes my problem, because this line does nothing:

noDataColor().removeNoDataLabelColor()

,even though it prints "Executed".

My question is: How can I remove my errLabel without using delegates.

Note: I use those lines in different class than noDataColor class.

Thank you :)

Upvotes: 0

Views: 298

Answers (1)

naglerrr
naglerrr

Reputation: 2854

Every time you call noDataColor()you create a new instance of your class.

noDataColor().addNoDataLabel(self.tableView, text: errorMessage!, color: .white)
noDataColor().removeNoDataLabelColor()

The second line creates a new instance of the noDataColor which has never had it's addNoDataLabel(_, text:, color:)called. You need to keep a reference of you class around:

let noDataColor = noDataColor()
noDataColor.addNoDataLabel(self.tableView, text: errorMessage!, color: .white)
noDataColor.removeNoDataLabelColor()

As you can see you need to call the methods on the same object.

Upvotes: 1

Related Questions