LilMoke
LilMoke

Reputation: 3444

UITableViewCell and repositioning UILabels in the cell

I have a UITableView and I have cells of different heights. I have overridden heightForRowAtIndexPath and I calculate the correct height by determine the UILabel height after a call to [lb sizeToFit]. I get the correct height for each cell, but I am a bit fuzzy on where the best place r=to reposition the UILabels is.

I have tried to reposition them in cellForRowAtIndexPath, but that does not seem to work. So, before I go too far down the road is this the right place? On the surface it does not to work.

Question: Is cellForRowAtIndexPath the correct place to resize and move my controls?

Thanks for any help.

Upvotes: 0

Views: 107

Answers (3)

danh
danh

Reputation: 62676

If you can get autolayout to work, then I think @Wain has the best idea. Sometimes the layout might be too complex for autolayout , in which case you'll need to do it in code.

Where in code? Your idea to do it in cellForRowAtIndexPath: is perfectly okay. Just remember that cells get dequeued in an arbitrary states left over from other rows, so you shouldn't depend on initial conditions. e.g.

UILabel *label3 = (UILabel *)[cell viewWithTag:100];
// give the subviews constant tags (not dependent on row for example)

if (/* this is a short cell, so the third label must be hidden */) {
    label3.alpha = 0.0;
}
// NOT DONE YET!

since we don't know the state of label3 when it's dequeued, we must cover every condition, by providing an else-block as the complement of the if-block.

else {
    // it must be a taller cell
    // or else if, if there are other sizes of cells, etc.
    label3.alpha = 1.0;
}

This might get very involved, and you might find it more readable to relocate this layout logic in your own UITableView subclass, which is @NickGalasso's good suggestion.

Upvotes: 0

Wain
Wain

Reputation: 119031

Determine the size that the label needs to be and return that height from your table delegate method.

In the cell, pin the label to the edges of the superview (the cell content view). You can do that either with auto resizing mask (flexible width + height) or with auto layout. In either case, that will make the label resize to the correct frame automatically without you doing anything else.

Upvotes: 1

Nick
Nick

Reputation: 2369

Create your own UITableViewCell subclass, and override layoutSubviews. Remember to call [super layoutSubviews]. Then layout the cell correctly for whatever amount of content you are displaying. (assume the cell will be given the correct frame)

In heightForRowAtIndexPath: you will need to perform that same calculation, based on how the cell lays out its content.

Upvotes: 1

Related Questions