Expand UILabel inside UITableView with “more” button like Instagram

前端 未结 1 1001
时光取名叫无心
时光取名叫无心 2020-11-30 07:21

I\'ve got a project (that has been written by other people) where there\'s a feed with content and text displayed inside a table view. Each post corresponds to one section i

相关标签:
1条回答
  • 2020-11-30 07:54

    Here is an example: https://github.com/DonMag/DynamicCellHeight

    Table B is one way of accomplishing "More/Less" (Table A was for another layout I played around with). It uses the [tableView beginUpdates]; tableView endUpdates]; method of triggering the table re-layout.

    The key is getting all your constraints set up correctly, so the Auto-Layout engine does what you expect.

    The example is in Swift, but should be really easily translated back to Obj-C (I think I did it in Obj-C first).

    Edit: some additional notes...

    This is using a pretty standard method of dynamic-height table view cells. The vertical spacing constraints between elements effectively "pushes out" the bounds of the cell. The tap here toggles the numberOfLines property of the label between 2 and 0 (zero meaning as many lines as necessary). Sequential calls to beginUpdates / endUpdates on the table view tells the auto-layout engine to recalculate the row heights without needing to reload the data.

    For this example, I did use a little "trickery" to get the smooth expand/collapse effect... The multiline label you see here is contained in a UIView (with clipsToBounds true). There is a second, duplicate multiline label (alpha 0 so it's not visible) that is controlling the height. I found that changing the numberOfLines on the visible label sort of "snapped" to 2 lines, and then the size change animation took place... resulting in the text "jumping around."

    Just for the heck of it, I added the "not so good" version to my GitHub repo for comparison's sake.

    0 讨论(0)
提交回复
热议问题