在UICollectionView中更新UILabel

时间:2015-12-16 18:46:42

标签: ios uicollectionview nstimer uicollectionviewcell uicollectionviewlayout

这是我的collectionView代码:

  func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath)
    let cellWidth = self.view.frame.size.width / 3 - 15
    cell.layer.cornerRadius = cellWidth / 15

    // Fetch final image - if it exists
    if let finalImage = collectedRows[indexPath.row]["picture"] as? PFFile {
      finalImage.getDataInBackgroundWithBlock {
        (imageData: NSData?, error: NSError?) -> Void in
        if error == nil {
          if let imageData = imageData {

            let imageView = UIImageView(frame: CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height))
            imageView.image = UIImage(data: imageData)
            imageView.contentMode = UIViewContentMode.ScaleToFill
            cell.addSubview(imageView)

            if #available(iOS 8.0, *) {
                if !UIAccessibilityIsReduceTransparencyEnabled() {
                  cell.backgroundColor = UIColor.clearColor()

                  let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Light)
                  let blurEffectView = UIVisualEffectView(effect: blurEffect)
                  //always fill the view
                  blurEffectView.frame = cell.bounds
                  blurEffectView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]

                  cell.addSubview(blurEffectView)
            } else {
                  let overLayer = UIView(frame: CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height))
                  overLayer.backgroundColor = UIColor.blackColor()
                  overLayer.alpha = 0.75
                  cell.addSubview(overLayer)
                }
            } else {
                // Fallback on earlier versions
              let overLayer = UIView(frame: CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height))
              overLayer.backgroundColor = UIColor.blackColor()
              overLayer.alpha = 0.75
              cell.addSubview(overLayer)
            }

            //Create time Left label

            if let sentDate = self.collectedRows[indexPath.row]["sentAt"] as? NSDate {
              print("sentDate: \(sentDate)")
              let calendar = NSCalendar.currentCalendar()

              if #available(iOS 8.0, *) {
                let expiryDate = calendar.dateByAddingUnit(.Day, value: 1, toDate: sentDate, options: NSCalendarOptions())
                let currentDate = NSDate()
                let differenceTime = calendar.components([.Day, .Hour, .Minute, .Second], fromDate: currentDate, toDate: expiryDate!, options: NSCalendarOptions())
                print("sendDate2: \(differenceTime)")
                let hoursLeft = String(differenceTime.hour)
                let minutesLeft = String(differenceTime.minute)
                let secondsLeft = String(differenceTime.second)

                if (Int(hoursLeft)! <= 0 && Int(minutesLeft)! <= 0 && Int(secondsLeft)! <= 0) {
                  //remove object from parse
                  self.collectedRows[indexPath.row].deleteInBackground()
                  self.collectedRows[indexPath.row].saveInBackground()
                } else {
                  let timerLabel = UILabel(frame: CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height))
                  timerLabel.font = UIFont(name: "SourceSansPro-Semibold", size: 16)
                  timerLabel.textAlignment = .Center
                  timerLabel.textColor = UIColor.whiteColor()
                  timerLabel.text = "\(hoursLeft):\(minutesLeft):\(secondsLeft)"
                  cell.addSubview(timerLabel)
                  cell.bringSubviewToFront(timerLabel)
                }
              } else {
                // Fallback on earlier versions
                let timerLabel = UILabel(frame: CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height))
                timerLabel.font = UIFont(name: "SourceSansPro-Semibold", size: 16)
                timerLabel.textAlignment = .Center
                timerLabel.textColor = UIColor.whiteColor()
                timerLabel.numberOfLines = 2
                timerLabel.text = "Less than \n24 Hours Left"
                cell.addSubview(timerLabel)
                cell.bringSubviewToFront(timerLabel)

              }
            }

            if #available(iOS 8.0, *) {
            let deleteButton = UIButton(frame: CGRectMake(cell.frame.size.width/2, cell.frame.size.height * 0.75, cell.frame.size.width/2, cell.frame.size.height/4))
            deleteButton.backgroundColor = UIColor.clearColor()
            deleteButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
            deleteButton.setTitle("...", forState: .Normal)
            deleteButton.titleLabel!.font = UIFont(name: "SourceSansPro-Bold", size: 32)
            cell.addSubview(deleteButton)
            deleteButton.addTarget(self, action: "removeFromProfile:", forControlEvents: UIControlEvents.TouchUpInside)
            } else {
              // DO NOT even show button
            }
            cell.layer.cornerRadius = cell.frame.size.width / 15
            cell.layer.masksToBounds = true
          }
        }
      }
    }
    return cell
  }

我正在创建一个UICollectionViewCell,它有一张模糊的照片和顶部的UILabel,这是一个24小时倒计时标签。一切正常。但是,我希望UILabel每秒更新一次,以便它不断倒计时。我知道我可以创建一个NSTimer来每秒更新整个UICollectionView(使用collection.reloadData())。这显然会导致内存问题并导致应用程序崩溃。有谁知道如何更新标签?或者是否有人知道如何从该方法中提取标签,然后将标签应用于适当的单元atIndexPath,然后使用NSTimer.scheduledWithInterval调用新方法(标签创建)?标记为:

的部分
//Create time Left label

是我每秒钟需要更新的唯一部分。

2 个答案:

答案 0 :(得分:1)

我建议在类中创建一个weak属性来保存对timerLabel的引用,并在cellForItemAtIndexPath函数中设置该属性。

您的计时器功能应该能够使用该属性更新标签而无需重新加载集合视图(只要它仍然是视图层次结构的一部分)。

答案 1 :(得分:0)

您应该创建一个自定义单元格类(也可以添加一个nib文件来清理那个混乱),添加一个计时器属性,然后您可以从cellForRowAtIndex启动计时器。不要忘记在deinitprepareForReuse中使计时器无效。

相关问题