Ios 使UITableView';s的高度取决于它';s单元';高度
我在Swift项目中有一张桌子Ios 使UITableView';s的高度取决于它';s单元';高度,ios,swift,uitableview,Ios,Swift,Uitableview,我在Swift项目中有一张桌子 tableView = UITableView() tableView.dataSource = self tableView.delegate = self tableView.estimatedRowHeight = 200 tableView.rowHeight = UITableViewAutomaticDimension func tableView(_ tableView: UITableView, cellForRowAt indexPath: I
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
}
单元格获得自动高度,但
tableView
的高度不是自动的如何使其自动?我不是只使用故事板的编程方法 您应该使用AutoLayout,并确保所有组件都锚定到contentView的顶部和底部,如下所示:
您可以使用
tableView.rowHeight = UITableViewAutomaticDimension // in your viewDidLoad
但请确保您没有为标签提供固定高度和宽度约束
您应该将numberOfLines设置为0。这样,您的标签将具有多行文字。通过实现适当的自动布局约束,您可以实现这一点this@karthikeyan它返回
estimatedRowHeight
乘以单元格数,获取高度并调整表格视图框架。如果使用自动布局,使用常量。@karthikeyan我将其更新为tableView.contentSize.height+tableView.contentInset.bottom+tableView.contentInset.top
以下是我执行此操作的结果,但当我将tableView的heightConstant保留为0时,它不会显示任何内容。您是否实现了此方法func tableView(uTableView:UITableView,HightForRowatIndeXPath:indexPath)->CGFloat{}
?如果是,让我们删除它。我已经删除了它