0

I am using a UITableViewController in my app. This works great, but I was wondering how I can do some small changes per device. The UITableViewCell height is not on all devices great. On iPhone 6/7 and Plus models it fits perfect, but on an iPhone SE/5 and 4 the rows are too big. I know that Interface Builder has a function called Vary of Traits, but when I select for example iPhone 4 and change the height of the UITableViewCell it will also be applied to all other sizes. So is this - different cell heights for different devices - possible and if yes, how can I add different cell heights based on different device heights?

Caspert
  • 4,271
  • 15
  • 59
  • 104
  • 1
    Don't base anything on the device model. Calculate the row height based on the height of the table view or its parent view. – rmaddy Jan 12 '17 at 18:56

2 Answers2

1

UITableView has a delegate method called heightForRowAt indexPath:

Within that method, you can write logic that defines the cell height as a proportion of screen height, tableView height, or whatever you need

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return // screenHeight (or tableViewHeight) / someNumberThatFitsYourNeeds
}
JAB
  • 3,165
  • 16
  • 29
  • And can you also tell me how to select for example only iPhone 4 or SE for an specific height? – Caspert Jan 12 '17 at 18:48
  • just check if screen height is equal to the height of the iPhone 4 / SE screens...if it is, return the desired cell height – JAB Jan 12 '17 at 18:50
  • Is there a property that holds these heights of iPhones? – Caspert Jan 12 '17 at 18:51
  • http://stackoverflow.com/questions/5677716/how-to-get-the-screen-width-and-height-in-ios – JAB Jan 12 '17 at 18:53
  • that's how to get the current device height. There is no property that holds the heights of other phones, you have to hard code it – JAB Jan 12 '17 at 18:54
  • 1
    No, do not hard code anything. Do not worry about device model. Simple base the row height on the height of the table view or the view controller's view. – rmaddy Jan 12 '17 at 19:02
  • suggested that in the answer – JAB Jan 12 '17 at 19:24
0

you can calculate height of cell at runtime in

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
}

for Example : let's assume that perfect cell height is 70 on Iphone 7 of view height 700,so you will code like

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        return self.view.frame.size.height * 0.1
}

so using this method your cell will always size 10% of your view's height

krishan kumar
  • 378
  • 6
  • 11