Search code examples
iosswiftautolayoutlayoutsubviewsuitableview

Reordering subviews programatically won't work in a tableViewCell


I'm trying to reorder an image and a stackview (here called labelsStack) that are both contained in another stackview (here called stack). My goald would be to programatically reverse the index order of both subviews in order to change their postition at runtime (they are horizontally distributed, so theorically, if I reorder their indexes, it should reorder them in autolayout)

I have tried to update indexes, exchange subviews, sendViewForward etc from the Apple doc, but it doesn t work, here s the code of my tableViewCell :

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


           }

    override func layoutSubviews() {
        cellImage.layer.cornerRadius = cellImage.bounds.height / 3
        cellImage.clipsToBounds = true

        if incoming {
        } else {
// as one of the many methods that didn't work
            self.stack.insertSubview(cellImage, belowSubview: labelsStack)
        }


    }

Solution

  • You could create two alternative sets of constraints, one for the default order and the other for the inverse order. The default constraints are the one ending in 1

    enter image description here

    To initially deactivate the alternative setting you can use the inspector and change the installed checkbox

    enter image description here

    Your view controller should now have 6 outlets:

    @IBOutlet weak var topViewTopConstraint1: NSLayoutConstraint!
    @IBOutlet weak var bottomViewTopConstraint1: NSLayoutConstraint!
    @IBOutlet weak var bottomViewBottomConstraint1: NSLayoutConstraint!
    
    @IBOutlet weak var topViewTopConstraint2: NSLayoutConstraint!
    @IBOutlet weak var bottomViewTopConstraint2: NSLayoutConstraint!
    @IBOutlet weak var topViewBottomConstraint2: NSLayoutConstraint!
    

    now to activate the other set of constraints you can use:

        self.topViewBottomConstraint2.active = true
        self.topViewTopConstraint2.active = true
        self.bottomViewTopConstraint2.active = true
        self.topViewTopConstraint1.active = false
        self.bottomViewBottomConstraint1.active = false
        self.bottomViewTopConstraint1.active = false
    

    and viceversa