Reputation: 1199
I am trying to automatically adjust the table view height in my project, by determining what kind of iPhone the user has. However, I am not quite sure how I would proceed in order to adjust the height. I have tried several methods such as self.tableView.rowHeight = 100
etc, but with no luck.
Could someone please point me in the right direction?
Thanks in advance.
Upvotes: 0
Views: 476
Reputation: 1508
First, create an extension to detect which iPhone is running the app:
extension UIDevice {
var iPhone: Bool {
return UIDevice().userInterfaceIdiom == .phone
}
enum ScreenType {
case iPhone4
case iPhone5
case iPhone6
case iPhone6Plus
case unknown
}
var screenType: ScreenType {
guard iPhone else { return .unknown }
switch UIScreen.main.nativeBounds.height {
case 960:
return .iPhone4
case 1136:
return .iPhone5
case 1334:
return .iPhone6
case 2208:
return .iPhone6Plus
default:
return .unknown
}
}
}
Then, in your controller, link the tableview delegate if you didn't do it yet:
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
Implement the delegate method like so to adjust height of cell depending on iphone type:
extension YourViewController: UITableViewDelegate {
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch UIDevice().screenType {
case .iPhone4:
return 40
default:
return 60
}
}
}
Upvotes: 1
Reputation: 473
Please this two delegate method of tableview in your view controller
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
Upvotes: 0