UITableviewCell - reload constraints after having removed a subview

Discussion in 'iOS Programming' started by dantastic, Dec 9, 2015.

  1. dantastic macrumors 6502

    dantastic

    Joined:
    Jan 21, 2011
    #1
    I have a UITbleViewCell with a few labels and image views using autolayout. It's populated by data from a feed and the feed doesn't contain data for all labels all the time. So in the code I do [self.myEmpyLabel
    removeFromSuperview] and autolayout automagically sorts the spacing so it all looks good.

    How do I reset everything again in the prepareForReuse???
    Do I have to keep track manually of all constraints and add them back or is there a way to just reset the cell?
     
  2. PhoneyDeveloper macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #2
    There is no way to reset the cell. Instead of removing the constraint you should set things up so that the label can have a 0 height or width, in the case of no data. I typically do this in cellForRowAtIndexPath.
     
  3. dantastic thread starter macrumors 6502

    dantastic

    Joined:
    Jan 21, 2011
    #3
    The problem with that is you get wonky distances between objects.

    I worked around the problem by saving the contentView constraints in the awakefromnib
    Then to 'reset' the cell in prepareForReuse I removeFromSuperview all contentView subViews. And then add all IBOutlets. (Need a strong reference to the IBOutlets or keep a reference in an array) Final step set the contentView.constraints back to the saved constraints.

    This was more accurate than trying to remember which fields had been removed and just add them back and their associated constraints.

    There sure are a lot of tricks to autolayout.
     
  4. PhoneyDeveloper macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #4
    There is an NSLayoutConstraint property called active that can be used to turn off constraints. The usual trick is to have two similar constraints where they have different priorities. You can choose between the one that is used by setting the active property. So you leave all the views and all the constraints. You disable those constraints that aren't needed. Saving and re-adding constraints doesn't sound right.
     
  5. dantastic thread starter macrumors 6502

    dantastic

    Joined:
    Jan 21, 2011
    #5
    I might look in to that. As much as my method works, I'm not happy with it.
     

Share This Page