Reputation: 4253
My objective is make a screen like this:
This is the screen that I've implemented with StackView and Labels. But now, I want to do this with a UITableView. My problem is that Cells needs to be dynamic. Because a text can be different from the others. So I've started creating a UITableViewCell with your xib file (the backgroud grey is to design)
Swift file
class CellCreateSaleVC: UITableViewCell {
@IBOutlet weak var lblInfo: UILabel!
@IBOutlet weak var imgClipboard: UIImageView!
@IBOutlet weak var lblNomeCampo: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
ViewController with UITableView
class CreateSaleViewController : UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableViewMenu: UITableView!
let options : Int = 12
override func viewDidLoad() {
tableViewMenu.dataSource = self
tableViewMenu.delegate = self
tableViewMenu.register(UINib(nibName: "CellCreateSaleVC", bundle: nil), forCellReuseIdentifier: "CellCreateSale")
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return options
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellCreateSale") as! CellCreateSaleVC
return cell
}
}
Upvotes: 2
Views: 3528
Reputation: 12023
For dynamic height TableViewCell you need to use self-sizing table view cells, you must set the table view’s rowHeight property to UITableViewAutomaticDimension
. You must also assign a value to the estimatedRowHeight
property.
tableView.estimatedRowHeight = 85.0
tableView.rowHeight = UITableViewAutomaticDimension
To define the cell’s height, add constraints to the views of cells from to to the bottom edge. If your views have intrinsic content heights, the system uses those values. If not, you must add the appropriate height constraints, either to the views or to the content view itself.
Note:
Additionally, try to make the estimated row height as accurate as possible. The system calculates items such as the scroll bar heights based on these estimates. The more accurate the estimates, the more seamless the user experience becomes.
Refer this excellent stack overflow answer for using auto layout for dynamic cell heights. and raywendelich.com tutorial on self sizing tableview cells.
Upvotes: 2