繁体   English   中英

编码的自动布局不适用于UITableView

[英]Coded auto-layout not working properly for UITableView

我正在使用UITableView处理提要页面,并且试图设置单元格的动态高度(以根据内容进行调整)。

我为单元格创建了一个自定义类,下面是代码:

class cellTableViewCell: UITableViewCell, UINavigationControllerDelegate {



//OUTLETS
@IBOutlet weak var usernameLbl: UILabel!
@IBOutlet var profileImg: UIImageView!



override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code



    usernameLbl.text = "Username"
    usernameLbl.textColor = UIColor.grayColor()

    profileImg.layer.cornerRadius = profileImg.frame.size.width/2
    profileImg.layer.masksToBounds = true


    profileImg.addConstraint(NSLayoutConstraint(item: profileImg, attribute: NSLayoutAttribute.Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1.0, constant: 100.0))

    contentView.addSubview(profileImg)

    contentView.addConstraint(NSLayoutConstraint(item: profileImg, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 100.0))




}

然后,在控制表格视图的View Controller的ViewDidLoad()方法中,添加了以下内容:

self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 160.0

但是,单元格根本无法适应,因为高度仍小于内容单元的高度。

我认为您的约束是完全正确的,但问题是您无法为每个单元格构建具有不同高度的动态TableViewCells的UITableView。 我自己尝试过,但是在动态UITableViewCell中,tableView的属性rowHeight(tableView.rowHeight)。 因此,该rowHeight将覆盖由Constraints定义的单元格的每个不同高度。

我找到了问题的答案:

您可以像这样使用UITableViewDelegate的函数'heightForRowAtIndexPath':

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM