动态细胞高度迅速

时间:2016-08-14 07:14:27

标签: swift uitableview

我的动态单元格高度有问题。这是我的代码,单元格不是动态高度,hơ使其动态(不是autolayout)。谢谢

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell: CustomCell = tableView.dequeueReusableCellWithIdentifier("customCell", forIndexPath: indexPath) as! CustomCell


        let label = UILabel(frame: CGRectMake(0 , 0, cell.frame.width, cell.frame.height))
        label.text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut eget libero enim. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Donec tempor posuere augue. Pellentesque at nibh quam. Mauris at nulla id enim elementum fermentum sit amet at dolor. Phasellus quis purus eu enim ullamcorper porttitor. Praesent consectetur lorem non ligula elementum rhoncus. Pellentesque diam dolor, gravida eget quam at, consequat luctus elit. Curabitur posuere augue sed nunc ornare semper. Nunc ut lorem vitae ligula dictum dapibus quis eget ex. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas."
        label.numberOfLines = 0
        label.sizeToFit()
        label.lineBreakMode = NSLineBreakMode.ByWordWrapping
        cell.contentView.addSubview(label)

        return cell
    }

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }
    func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }

4 个答案:

答案 0 :(得分:1)

您可以使用boundingRectWithSizeNSString

NSAttributedString方法
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    let text: NSString = ""
    let size = CGSize(width: widthOfYourCell, height: CGFloat.max)
    let attributes: [String : AnyObject] = [
        NSFontAttributeName : UIFont.systemFontOfSize(15)
        // etc.
    ]
    let rect = text.boundingRectWithSize(size, options: .UsesLineFragmentOrigin, attributes: attributes, context: nil)
    return rect.height
}

答案 1 :(得分:1)

您必须添加以下代码:

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.rowHeight = UITableViewAutomaticDimension;
        self.tableView.estimatedRowHeight = 44.f; // As your mind.
    }

答案 2 :(得分:0)

只需添加tableview的这两个委托方法,并记住magic.keep不要给任何属性的固定高度。

 func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}

func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 500
}

答案 3 :(得分:0)

SWIFT 3.0中的

首先,您已设置标签约束,例如leading,traling,top和bottom

然后在 ViewController.swift 文件中设置约束后

方法 ViewDidLoad()编写此代码。

yourTableview.estimatedRowHeight = 83.0

yourTableview.rowHeight = UITableViewAutomaticDimension