[英]Dynamic table view cell, change of subview height programmatically
我有一个带有自定义视图单元格的UITableViewCell
。 在此视图单元中,我有一个名为imgWrapper的简单UIView
,在其中添加了约束,如下所示:
这些是那里的唯一约束。 我将拥抱和压缩保留为默认值。
在我的代码中,我将其设置为:
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 90
}
然后在我的rowAtIndex中...
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: LogCustomCell = tableView.dequeueReusableCellWithIdentifier("logCustomCell", forIndexPath: indexPath) as! LogCustomCell
var imgWrapperHeight: CGFloat = log.big ? 100 : 50
cell.imgWrapperHeight.frame.size.height = imgWrapperHeight
return cell
}
一旦我编译并运行它。 所有单元格大小相同。
笔记:
CGRect(x,y,width,height)
但也没有用。 heightForRowAtIndexPath
但我想做动画,我知道我们可以对标签做类似的事情(请参见printscreen),这使得tableView知道高度而无需定义它: 有什么想法我做错了吗?
您需要将高度逻辑放入名为tableView:heightForRowAtIndexPath
的UITableViewDelegate
方法中,如下所示:
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return (true ? 100 : 50) + 2 * 20
}
PS。 我已经在Swift 2中编写了此代码,因此使用了override
关键字。
委托方法“ heightForRowAtIndexPath”将为您完成。 您可以知道要从indexPath.row返回高度的单元格索引,并因此返回高度。
即
if indexPath.row == 0
{
return 70
}
else if indexPath.row == 1
{
return 100
}
加
self.automaticallyAdjustsScrollViewInsets = false
在这两行之前
tableView.estimatedRowHeight = 50
tableView.cellHeight = UITableViewCellAutomaticDimension
解决方案1:
如用户所提及。 您可以像这样在UITableViewController中设置行高:
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return (true ? 100 : 50) + 2 * 20
}
解决方案2:
在确定单元格高度的元素上设置height
约束。 然后在VC中为NSLayoutConstraint
创建一个插座。在设置单元格的内容时,您可以执行以下操作:
例如:@IBOutlet var imgWrapperHeightConstraint:NSLayoutConstraint!
...
override func tableView(tableView: UITableView, cellAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
imgWrapperHeightConstraint.constant = 50 // Or whatever value you want
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.