想实现让cell 根据label里的数据自动调整高度让label多行显示数据,根据网上给的自适应方法没有实现,还希望伙伴们给点指导,下面附上代码和截图
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableView.rowHeight = UITableViewAutomaticDimension
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// func tableView(tableView: UITableView,heightForRowAtIndexPath indexPath:NSIndexPath)->CGFloat{
// return 44
// }
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return 5
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell : TableViewCell! = tableView.dequeueReusableCellWithIdentifier("Cell") as! TableViewCell
if(cell == nil)
{
cell = NSBundle.mainBundle().loadNibNamed("Cell", owner: self, options: nil)[0] as! TableViewCell;
}
cell.first.text = "nnfsfhsdsdsdifsfsfsdfisfsidfhsdfhdhfsdfsdfhdfhhfhsdfhsdhfshdhsdfsdd"
cell.second.text = "rirgjf"
cell.frame.size.height = cell.first.frame.size.height
return cell as UITableViewCell
}
}
import UIKit
class TableViewCell: UITableViewCell {
@IBOutlet weak var first: UILabel!
@IBOutlet weak var second: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
动态设定cell的高度,自己依据文本的内容,字体大小,指定宽度计算label的size,然后返回给tableView的cell高度的代理就可以。
楼上正解,他给的代码是正确的。顺便提一下,如果是在iOS6系统中运行,是没有boudingRectWithSize.....那个方法的,它只适用于iOS7及以上版本的系统。iOS6系统的话,此时很简单,调用sizeWithFont.....方法即可。不过,现在iOS9都出来了,不用适配iOS6了吧,太老了
cell的自适应有更简单的方法,就是你写的那个,self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 2(数字随便给);还要给label设置约束