使UITableView的高度取决于它的单元格高度

时间:2017-03-24 08:16:09

标签: ios swift uitableview

我的Swift项目中有一张表

tableView = UITableView()
tableView.dataSource = self
tableView.delegate = self
tableView.estimatedRowHeight = 200
tableView.rowHeight = UITableViewAutomaticDimension 
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell  = UITableViewCell()
        let ProfilePicture = UIImageView()
        ProfilePicture.image = #imageLiteral(resourceName: "cole")
        ProfilePicture.layer.cornerRadius = 25
        ProfilePicture.layer.masksToBounds = true

        let username  = UILabel()
        username.text = posters[indexPath.row]
        username.textColor = UIColor(r: 68, g: 68, b: 85)
        username.font = UIFont(name: "AppleSDGothicNeo-Light", size: 18)
        username.numberOfLines = 0

        let postText = UITextView()
        postText.text = postTexts[indexPath.row]
        postText.textColor = UIColor(r: 83, g: 92, b: 87)
        postText.font = UIFont(name: "Courier", size: 15)
        postText.isScrollEnabled = false
        postText.isUserInteractionEnabled = false

        let border = UIView()
        border.backgroundColor = UIColor(r: 17, g: 221, b: 219)


        cell.addSubview(ProfilePicture)
        cell.addSubview(username)
        cell.addSubview(postText)
        cell.addSubview(border)

        ProfilePicture.anchor(cell.topAnchor, left:cell.leftAnchor, bottom: nil, right: nil, topConstant: 15, leftConstant: 14, bottomConstant: 0, rightConstant: 0, widthConstant: 50,heightConstant:50)
        username.anchor(cell.topAnchor, left:ProfilePicture.rightAnchor, bottom: postText.topAnchor, right: cell.rightAnchor, topConstant: 20, leftConstant: 13, bottomConstant: 0, rightConstant: 15, widthConstant: 0,heightConstant:20)
        postText.anchor(username.bottomAnchor, left:ProfilePicture.rightAnchor, bottom:nil, right: cell.rightAnchor, topConstant: 0, leftConstant: 15, bottomConstant: 0, rightConstant: 15, widthConstant: 0)
        border.anchor(postText.bottomAnchor, left:cell.leftAnchor, bottom: cell.bottomAnchor, right: cell.rightAnchor, topConstant: 20, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0,heightConstant:1)
        cell.layoutIfNeeded()
        cell.sizeToFit()
        return cell
    }

Cell获得自动高度,但tableView的高度不是自动的,我怎样才能使它自动化?我不是只使用故事板编程方法。

2 个答案:

答案 0 :(得分:1)

您应该使用AutoLayout并确保所有组件都锚定到contentView的顶部底部,如下所示:

enter image description here

答案 1 :(得分:0)

您可以使用

制作动态单元格,该单元格将取决于标签的高度
tableView.rowHeight = UITableViewAutomaticDimension // in your viewDidLoad 

但请确保您没有为标签提供修正高度和宽度约束。

你应该设置numberOfLines = 0.这样你的标签就会有多行文字。