UITableViewController with different Cell sizes and Cell content in Storyboard

橙三吉。 提交于 2019-12-25 08:20:10

问题


I want to make a UITableViewController with different Cell sizes and different content of the cells.

For example:

Is there a way to use AutoLayout within the Storyboard to define the different sizes of the TableViewCells? What would be the best way to define the content (a UIView with content on it) of the TableViewCells?


回答1:


To change the cells of the UITableView, you have 2 options:

Option A (best) is to use Autosizing TableView Cells with Autolayout Constraints.

To use option A, you need to make sure your cell contentview has clear top & bottom constraints to all your UI elements in the content View (see my image here) as an example:

The Title UILabel has a top space to the superview (Cell ContentView) and a vertical spacing with the SubTitle. The SubTitle has also a bottom space constraint to the superview (Cell ContentView).

This allows the cell to be autoresized as my UI elements have top & bottom constraints to the content view.

Final step to enable the autosizing is to set these 2 properties in your UITableView:

self.tableView.estimatedRowHeight = 60.0;
self.tableView.rowHeight = UITableViewAutomaticDimension;

The estimatedRowHeight value should be as close as you can guess to the real size, this helps speed up calculations a bit.

Option B is to add the - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath; delegate to your UIViewController.

There you should be manually providing the height of the cell. If you are using just 2 different cells with 2 fixed heights, you can use option B as well and there you add a logic to detect the cell and return the height...

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if ([cell isKindOfClass:[MyCustomCellTypeAClass class]]) {
        return 44;
    }
    else {
        return 100;
    }
}



回答2:


If you are using auto-layout, height will be calculated using constraints (if you set them properly); and you have to use delegate method as following -

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}



回答3:


Use storyboard? do your mean like this? enter image description here

Maybe i should provided a demo(StackOverFlowQuestions02) to be clear. for more details --->link:

https://github.com/tingxins/StackOverFlowQuestions

I believe that running demo and you will get it.



来源:https://stackoverflow.com/questions/40606539/uitableviewcontroller-with-different-cell-sizes-and-cell-content-in-storyboard

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