【发布时间】:2014-07-31 09:00:09
【问题描述】:
我有很多行,有几种不同的布局 - 一切正常。现在我想在一些行上添加一个自定义UILabel。我知道使用重用标识符存在“问题”,因此UITableView 将尝试在下一个单元格上再次重用我的UILabel。为了防止这种情况,我在这里检查了很多建议并尝试了这种方式:
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell? {
var cell = tableView .dequeueReusableCellWithIdentifier(myQuestions.getQuestion(indexPath.row).qTemplate, forIndexPath: indexPath) as CustomTableViewCell
// if there is a saved Notice, add this to this Cell
if(myQuestions.getQuestion(indexPath.row).qNotice != nil) {
cell.addNoticeToCell("This is a Test")
}
return cell
}
而我的CustomTableViewCell 班级是:
class CustomTableViewCell: UITableViewCell {
@IBOutlet var LabelCellTitle: UILabel!
@IBOutlet var TextView: UITextView!
@IBOutlet weak var LabelCellContent: UILabel!
var noticeButton:UIButton!
func addNoticeToCell(noticeText: String) {
noticeButton = UIButton.buttonWithType(UIButtonType.System) as UIButton
noticeButton.frame = CGRectMake(330,44,600,44)
noticeButton.titleLabel.textColor = UIColor.blueColor()
noticeButton.tag = 100
noticeButton.setTitle(noticeText, forState: UIControlState.Normal)
self.contentView.addSubview(noticeButton)
}
override func prepareForReuse() {
println("CELL BEFORE REUSE")
if(self.contentView.subviews.count > 0) {
for mySubView in self.contentView.subviews {
if mySubView.tag == 100 {
mySubView.removeFromSuperview()
....
它现在按预期工作 - 但我不知道浏览所有子视图是否是个好主意。有没有更好的办法?我也会在某些单元格上添加 2-3 个UIImageViews,并使用相同的过程创建它。
【问题讨论】:
标签: ios swift uitableview cocoa-touch uilabel