2016-04-21 34 views
1

我正在尝试以编程方式创建一个具有动态大小和视图的表。问题是自动高度不起作用。我如何确保单元格高度保持正确,当我创建具有更多视图的单元格时。如何在Swift中创建动态大小的UITableViewCell?

这里是什么样子: Here is what it looks like:

这里是我的代码:

import SnapKit 
class FeedTableViewController: UITableViewController { 
    override func viewDidLoad() { 
     super.viewDidLoad() 
     tableView.rowHeight = UITableViewAutomaticDimension 
     tableView.estimatedRowHeight = 500 
     tableView.allowsSelection = false 
    } 

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCellWithIdentifier("appDataCell", forIndexPath: indexPath) as! AppDataTableViewCell 
     let view = cell.inner 
     cell.ivLogo.kf_setImageWithURL(NSURL(string: "http://creativosestrategicos.com/wp-content/uploads/2015/08/sample-logo-black16-300x58.png")!) 
     cell.tvLabel.text = "Post Title" 


     let label = UILabel() 
     label.text = "Test" 
     view.addSubview(label) 
     label.snp_makeConstraints { (make) in 
      make.top.equalTo(view) 
      make.left.equalTo(view) 
      make.right.equalTo(view) 
     } 

     return cell 
    } 
} 

这是我的故事板: Here is my storyboard

+0

此链接可能会帮助您计算动态单元格的高度 http://stackoverflow.com/ a/36095091/3918500 –

回答

0

应覆盖高度方法

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 
     return 100 /// 100 is your value here 
    } 
+0

但它不是静态的。视图以编程方式添加,因此它应该是动态大小。 –

+0

计算值并将其传递给该函数,然后 –

+0

我更喜欢使用UITableViewAutomaticDimension,因为内部视图会变得非常复杂,并且计算值将会很困难。 –

0

您正在使用错误的委托方法使用tableView:estimatedHeightForRowAtIndexPath:并返回UITableViewAutomaticDimension.This将只在您给出正确的约束时才起作用

相关问题