在collectionViewCell中设置出口之前的属性

时间:2015-08-02 10:00:27

标签: ios xcode swift

我的目标是在设置IBOutlets之前设置collectionViewCell的属性。 我试着先在cellForRowAtIndexPath中设置它,就像那样:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(Ids.Main.PollCell, forIndexPath: indexPath) as! PollCell
        let image = contentImages[indexPath.row]
        let count = scores[image.associatedStack]
        let isBestScore = count == bestScore
        cell.associatedImage = image
        cell.bestScore = isBestScore
        cell.count = count != nil ? count! : 0
        return cell
    }

然后,当设置插座时,我会通过didSet更新他们的UI:

@IBOutlet weak var image: DesignableImageView!{
        didSet{
            image.layer.cornerRadius = 35
            image.layer.masksToBounds = true
            if isCellSelected{
                image.layer.borderColor = UIColor.blueColor()
            } 
        }
    }
    @IBOutlet weak var countLabel: DesignableLabel!{
        didSet{
            countLabel.layer.cornerRadius = 7
            countLabel.layer.masksToBounds = true
            if bestScore {
                countLabel.backgroundColor = UIColor.yellowColor()
            }
            countLabel.text = "\(count)"
            countLabel.hidden = !didVote
        }
    }
    var associatedImage: StackImage?
    var bestScore = false
    var didVote = false
    var count = 0
    var labelText = "0"
    var imageIsSet = false
    var isCellSelected = false

问题是出口设置在属性之前! 这怎么可能 ? 我该如何设置属性然后从它设置出口? 是因为我的细胞已经出列了?

1 个答案:

答案 0 :(得分:1)

如果您的单元格在InterfaceBuilder中定义,那么将始终在awakeFromNib中设置插座,这将在您的代码之前调用。 didSet几乎肯定不是你正在做的事情的一半。您应该将它用于视图的初始设置,这些视图在重用之间不会发生变化。

为什么不将didSet添加到bestScore之类的内容中,然后您可以在这些位置进行适当的配置?

var bestScore = false {
  didSet {
    if bestScore {
      countLabel.backgroundColor = .yellowColor()
    } else {
      countLabel.backgroundColor = .whiteColor()
    }
  }
}