Search code examples
iosswiftuiviewswift4.1

Private variables value is resting in CustomView in ios swift


I am trying to create a customView using xib below is the code

import UIKit

class CustomView: UIView {

@IBOutlet var CustomView: UIView!

private var _isSelecteda:Bool!
var isSelecteda: Bool {
    get {
        return _isSelecteda
    }
    set {
        _isSelecteda = isSelecteda
        if _isSelecteda {
            CustomView.backgroundColor = UIColor.white
            CustomView.layer.borderColor = UIColor.black.cgColor
        }
        else {
            CustomView.backgroundColor = Colors.searchGameCellBackgroundColor
            CustomView.layer.borderColor = Colors.priceLabelBorderColor?.cgColor
        }
    }
}



override init(frame: CGRect) {

    super.init(frame: frame) 
    commonInit()

}

required init?(coder aDecoder: NSCoder) {

    super.init(coder: aDecoder)
    commonInit()

}


private func commonInit() {
    Bundle.main.loadNibNamed("CustomView", owner: self, options: nil)
    addSubview(CustomView)
    self._isSelecteda = false
    CustomView.layer.cornerRadius = 3
    CustomView.layer.borderWidth = 1
    self.clipsToBounds = true
    CustomView.frame = self.bounds

}

@IBAction func btnSelectedTapped(_ sender: Any) {
    isSelecteda = !isSelecteda
}
}

When ever I try to access isSelecteda the private declaration of _isSelecteda is called and resets the value . My objective is to set the value of isSelected from a ViewController and change its background color.

According to my understanding that should not be the case. Its very strange

Note : I am using Xcode 9.4.1 with Swift 4.1


Solution

  • Why not use didSet for that?

    didSet {
        if isSelecteda {
            CustomView.backgroundColor = UIColor.white
            CustomView.layer.borderColor = UIColor.black.cgColor
        } else {
            CustomView.backgroundColor = Colors.searchGameCellBackgroundColor
            CustomView.layer.borderColor = Colors.priceLabelBorderColor?.cgColor
        }
    }
    

    The reason for your value being reset is probably because your variable still has the oldValue which you are using for comparison inside the setter. When you call the variable inside the setter, the getter gets the oldValue because the newValue has not yet been set.


    Note: It's preferable to follow the naming conventions as per the official naming guidelines. Variables are lower camel case. CustomView -> customView.