how to set table cell height dynamically depending on text label length?

前端 未结 4 1900
终归单人心
终归单人心 2020-12-29 09:01

I am trying to learn Obj-C and iOS programming, but am still very new. I decided to try and make a simple Reddit client application. I am trying to display the front page po

4条回答
  •  既然无缘
    2020-12-29 09:35

    You should check out the documentation reference for

    -[UITableViewDelegate tableView:heightForRowAtIndexPath:]
    

    Essentially, you will need to measure the text yourself in order to return the correct dimensions for each table row. If they're simple NSStrings, which they appear to be from your screenshot, you can use the NSString UIKit Additions to measure them, e.g.

    -[NSString sizeWithFont:constrainedToSize:]
    

    Where the constrained size could have infinite height but the width of your table cell's content view.

    If they are attributed strings, there is a similar method in the NSAttributedString UIKit additions called boundingRectWithSize:options:context:

提交回复
热议问题