【问题标题】:Add Label To Cell on Certain Rows only仅在某些行上向单元格添加标签
【发布时间】: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


    【解决方案1】:

    prepareForReuse() 中,为什么不直接使用您添加到单元类的属性来删除它,而不是像这样枚举所有子视图:

    var noticeButton:UIButton?
    
    override func prepareForReuse() {
        super.prepareForReuse()
        if let notice = self.noticeButton {
            notice.removeFromSuperview()
            self.notice = nil
        }
    }
    

    【讨论】:

    • 感谢您的回复。我首先尝试过,但它总是给我一个错误:EXC_BAD_INSTRUCTION - 致命错误:在展开可选值时意外发现 nil
    • 那是因为你有 noticeButton 作为一个隐式展开的可选,而它应该被视为一个普通的可选。我会更新我的回复
    • 好的,谢谢 - 我明白了。我将您的文字更改为:self.noticeButton = nil - 现在可以按预期工作!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多