简体   繁体   English

制作表格视图单元格以完全在Swift中填充屏幕

[英]Make Table View Cells to fill up the screen exactly in Swift

I have three cells in my UITableView which I built in the storyboard, when I run it I have got three cells as expected in the simulator and then blank space underneath. 我在情节UITableView中构建的UITableView有三个单元格,运行它时,我在模拟器中按预期有三个单元格,然后在下面留有空白。 What I want to do is have the cells to dynamically fill up the screen depending on the iOS device. 我要做的是根据iOS设备使单元动态填充屏幕。 How do i do that? 我怎么做?

在此处输入图片说明

Set a minimum height for the cell, if there are few items, use even height, otherwise use minHeight. 设置单元格的最小高度,如果项目很少,则使用均匀高度,否则使用minHeight。

let MinHeight: CGFloat = 100.0
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    let tHeight = tableView.bounds.height

    let temp = tHeight/CGFloat(items.count)

    return temp > MinHeight ? temp : MinHeight
}

Update for Swift 5: Swift 5更新:

let minRowHeight: CGFloat = 100.0

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    let tHeight = tableView.frame.height
    let temp = tHeight / CGFloat(items.count)
    return temp > minRowHeight ? temp : minRowHeight
}

Is there a reason you are using a UITableView for this? 您有理由使用UITableView吗? The TableView really doesn't buy you any real benefits if you are going to fit it onto the screen and aren't going to have a variable number of cells with the ability to scroll. 如果要将TableView放到屏幕上并且不具有可变数量的具有滚动功能的单元格,则TableView确实不会为您带来任何实际好处。

If you simply want to have 3 views, each with 1/3 of the screen height, you could simply use IB to set up each view to be 1/3rd of the screen using the method in this answer 如果你只是想有3次,每次与屏幕高度的1/3,你可以简单地使用IB来设置每个视图是使用方法在屏幕的1/3 这个答案

Or if you want to use autolayout, which is the better solution, you can do it using this technique . 或者,如果您想使用自动布局,这是更好的解决方案,则可以使用此技术来实现

UITableViewDataSource设置- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath方法,以根据UITableView内容高度的高度计算行的高度。

在您的viewDidLoad方法中设置零高度的页脚视图。

tableView.tableFooterView = UIView()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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