简体   繁体   中英

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.

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.

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.

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. eg

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM