user3395936
user3395936

Reputation: 681

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. What I want to do is have the cells to dynamically fill up the screen depending on the iOS device. How do i do that?

enter image description here

Upvotes: 1

Views: 5918

Answers (4)

dichen
dichen

Reputation: 1633

Set a minimum height for the cell, if there are few items, use even height, otherwise use 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:

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
}

Upvotes: 9

Muzahid
Muzahid

Reputation: 5186

Set zero height footer view at your viewDidLoad method.

tableView.tableFooterView = UIView()

Upvotes: 0

Rwhoot
Rwhoot

Reputation: 61

In your UITableViewDataSource set up the - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath method to calculate the height of the rows based on the height of the UITableView's content height.

Upvotes: 0

wottle
wottle

Reputation: 13619

Is there a reason you are using a UITableView for this? 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.

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

Or if you want to use autolayout, which is the better solution, you can do it using this technique.

Upvotes: 1

Related Questions