我需要垂直添加標籤並且它們的編號是動態的。現在它可以正常使用此代碼:TableViewCell中元素的動態數量
let numUnitsLabel = UILabel(frame: CGRectZero)
numUnitsLabel.text = units
numUnitsLabel.font = UIFont.boldSystemFontOfSize(28)
numUnitsLabel.textColor = UIColor.redColor()
numUnitsLabel.translatesAutoresizingMaskIntoConstraints = false
cell.contentView.addSubview(numUnitsLabel)
let topConstraint = NSLayoutConstraint(item: numUnitsLabel, attribute: .Top, relatedBy: .Equal, toItem: cell.contentView, attribute: .Top, multiplier: 1, constant: 8 * CGFloat(i+1) + CGFloat(i*25) + CGFloat(i*20) - 5)
let rightConstraint = NSLayoutConstraint(item: numUnitsLabel, attribute: .Trailing, relatedBy: .Equal, toItem: cell.contentView, attribute: .Trailing, multiplier: 1, constant: -10)
cell.contentView.addConstraints([topConstraint, rightConstraint])
單元格繪製正常。但是,當我在列表中添加新項目並致電tableView.reloadData
時,舊標籤被「記住」並且它們超過了新標籤。新添加的對象放在數組中的第一個位置,它們就像一個在另一個...也許我的方法是不好的,但如果你有任何建議,請指教我。
您可以繼承tableviewcell並在prepareforreuse方法中刪除子視圖。 –
好的,但在循環中我有上面的代碼,所以基本上我添加標籤X次。我subclassed prepareForReuse現在如何刪除所有這些? – Slavcho
如果你的標籤是在類中定義的,你可以說numUnitsLabel.removeFromSuperview()。如果你想刪除單元格中的所有內容: 以查看contentView { view.removeFromSuperview() } –