Twitter khuong291
Twitter khuong291

Reputation: 11682

How to update frame of view in cell

I have a cell that has 1 label inside it.

I want when to show this label left then right, then left, then right...

Here is my code:

class CustomTableViewCell: UITableViewCell {

    @IBOutlet weak var titleData: UILabel!

    var data: String? {
        didSet {
            titleData.text = data ?? ""
            if alternativeMode {
                titleData.frame.origin.x = (row % 2 != 0) ? 200 : 0
            } else {
                titleData.frame.origin.x = 200
            }
            layoutSubviews()
        }
    }

    var row: Int!
    var alternativeMode = false

    override func layoutSubviews() {
        super.layoutSubviews()
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
        self.selectionStyle = .none
    }

}

But this label doesn't show alternative.

Upvotes: 1

Views: 1203

Answers (1)

Twitter khuong291
Twitter khuong291

Reputation: 11682

I have solved this problem in another approach

class CustomTableViewCell: UITableViewCell {

    @IBOutlet weak var titleData: UILabel!
    @IBOutlet weak var titleDataTrailingConstraint: NSLayoutConstraint!

    var data: String? {
        didSet {
            titleData.text = data ?? ""
        }
    }

    var row: Int! 
    var alternativeMode = false 

    override func layoutSubviews() {
        super.layoutSubviews()

        if titleDataTrailingConstraint != nil {
            let screenSizeWidth = UIScreen.main.bounds.width
            if alternativeMode {
                titleDataTrailingConstraint.constant = (row % 2 == 0) ? (screenSizeWidth - titleData.bounds.width - 80) : 10
            } else {
                titleDataTrailingConstraint.constant = 10
            }
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
        self.selectionStyle = .none
    }

}

Upvotes: 1

Related Questions