[英]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.