Grouped UITableView and horizontal margins

断了今生、忘了曾经 提交于 2019-12-12 09:53:43

问题


I have a grouped UITableView that was really designed to look nice in portrait mode for iPhone. Its cell subviews have autosizing set up so that they stretch in landscape mode, but this makes it a lot less aesthetically pleasing -- the cells just look too wide for their content.

I'm now making it a universal app but on iPad the autosizing causes even more stretching and it looks just unacceptable.

It would be ideal if I could make the UITableView's groups of cells have a fixed width (or a max width), or if I could somehow control the horizontal margins.

Having not found support for this in UITableView, I have done a few quick attempts at subclassing it to constrain its size at layout time and, as an alternative, at introducing a container view in order to make the UITableView autoresize vertically only. Both approaches work but create new problems: Scrolling doesn't work when swiping in the margins, and I am now forced to make the UITableView's background transparent (which goes against Apple's recommendations) as there is now a discontinuity of background between the UITableView's frame and the margins.

Has anyone found a trick to solve my problem (i.e. constrain the width of the groups in a UITableView, causing margins to expand to fill the width of the view), or an open source solution to it?


回答1:


Good news! I finally found a way to achieve this satisfactorily with only tiny code changes:

  • Shrink the cells by subclassing UITableViewCell and overriding -setFrame, as per the solution to this post:
    How to set the width of a cell in a UITableView in grouped style
  • And to add vertical padding, using the contentInset property of the UITableView (inherited from UIScrollView) works pretty well.



回答2:


You can always keep the standard table view and provide custom backgrounds with transparent sides for the table view cell's so that they look smaller than they are.

Cocoa With Love has a great article on how to do that here: Easy custom UITableView drawing.

The basic gist of the article is that you need to make six different versions of the backgrounds, and supply the correct one when tableView:cellForRowAtIndexPath: asks for a cell. You will need one with rounded corners at the top (for the first row of a section), one with rounded corners at the bottom (for the bottom row of a section), and one with all four corners rounded (for when there is only one row in the section). Then you will need the same three, but customized for the "selected" version of each row.



来源:https://stackoverflow.com/questions/11399402/grouped-uitableview-and-horizontal-margins

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!