我想使用 heightForRowAtIndexPath
获取表格单元格的高度。我的原型(prototype)单元中有两个标签和一张图像。这是 Storyboard:
我在使用 tableView.estimatedRowHeight = 100
和 tableView.rowHeight = UITableViewAutomaticDimension
时遇到问题,因为单元格的大小变化很大,所以我想手动执行此操作。我认为最好根据上图中显示的标题标签或作者标签来调整其大小,因为图像将是静态大小。
有很多 Objective-C 答案,但我无法让它发挥作用。关于如何使用 Swift 做到这一点有什么想法吗?
最佳答案
我也做了同样的事情来帮助你。请检查一下:
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableView.estimatedRowHeight = 132.0
self.tableView.rowHeight = UITableViewAutomaticDimension
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! TableViewCell
if indexPath.row == 0 {
cell.myTitle.text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
}
cell.myTitle.numberOfLines = 0
cell.myAuthor.numberOfLines = 0
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
}
希望它能帮助您解决问题。
关于ios - 根据内容获取表格单元格的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35471849/