Home > Software engineering >  Cannot change the variable
Cannot change the variable

Time:07-19

Hello guys I'm creating a custom text label and I can't change labels text from viewcontroller so I need help.

There is codes from my custom text labels swift file:

import UIKit

class LinkLabel: UILabel {
    
    private var labelFirstText: String? = "First Text"
    private var labelSecondText: String? = "Second Text"
    
    var firstLabel: String? {
        didSet {
            self.labelFirstText = firstLabel
        }
    }
    var secondLabel: String? {
        didSet {
            self.labelSecondText = secondLabel
        }
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupLabel()
        self.setNeedsDisplay()
    }
    
    @objc
    private func setupLabel() {
        let firstTextNSA = [NSAttributedString.Key.font:
                                UIFont.systemFont(ofSize: 15, weight: .medium),
                            NSAttributedString.Key.foregroundColor: UIColor.secondaryTextColor]
        let secondTextNSA = [NSAttributedString.Key.font:
                                UIFont.systemFont(ofSize: 15, weight: .medium),
                             NSAttributedString.Key.foregroundColor: UIColor.appPurple]
        let attributedString1 = NSMutableAttributedString(string: labelFirstText ?? "First Label"   " ", attributes: firstTextNSA)
        let attributedString2 = NSMutableAttributedString(string: labelSecondText ?? "Second Label", attributes: secondTextNSA)

        attributedString1.append(attributedString2)
        self.attributedText = attributedString1
    }

}

And there is my viewcontroller:

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet private weak var signInLabel: LinkLabel!
    
    // MARK: - Life Cycle
        override func viewDidLoad() {
            super.viewDidLoad()
            signInLabel.firstLabel = "Already have an account?"
            signInLabel.secondLabel = "Sign in now"
        }
}

Everything is work right now but just I can't change the label text. I write print functions for log what happen and see when didset run, the labelFirstText is "Already have an account?" but when init function run labelFirstText take default value. I don't understand how can I fix that.

CodePudding user response:

Add a call to setupLabel() immediately after any of the values are changed:

var firstLabel: String? {
    didSet {
        self.labelFirstText = firstLabel
        setupLabel()
    }
}

var secondLabel: String? {
    didSet {
        self.labelSecondText = secondLabel
        setupLabel()
    }
}
  • Related