【问题标题】:Format Int Array as String in cellForRowAtIndexPath Swift在 cellForRowAtIndexPath Swift 中将 Int 数组格式化为字符串
【发布时间】:2016-01-28 19:43:11
【问题描述】:

我正在获取以秒为单位存储在 Int 数组中的时间值,并尝试将其放在 UILabel 上,然后由 countDown 函数触发倒计时。我无法获得在每个单元格中倒计时的时间,也无法打印数组而不获取原始秒值而不格式化它,如下所示。现在我只能在每个单元格的 UILabel 上显示原始值:6532(小时、分钟、秒)

尝试在for loop 中单独打印数组时,我也无法格式化数组,如下所示。数组存储为 Int。

在 countDown 函数中使用 for 循环时,我可以将时间格式打印到日志中:HH:MM:SS。但并非如此。

这是我的倒计时功能:

func countDown() {
    //timerInt is an array where I'm storing the Int values.
    for i in 0 ..< timerInt.count {
        let hours = timerInt[i] / 3600
        let minsec = timerInt[i] % 3600
        let minutes = minsec / 60
        let seconds = minsec % 60
        print(String(format: "%02d:%02d:%02d", hours, minutes, seconds))

        timerInt[i]--
        print(self.timerInt[i])
    }
}

我正在尝试在 cellForRowAtIndexPath 方法中执行此操作。 UILabel 位于一个单独的类中:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let myCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! cell


 //This is the first item i'm posting on a UILabel and it works fine.
    myCell.productName.text = productName[indexPath.row]

        /*This cell/label I'm unable to format like in the for loop 
          which is formatted as a string*/

         myCell.secondLabel.text = ("\(intArray[indePath.row])")

         /*how do I format the intArray here so that the time 
           appears HH:MM:SS?? */



    return myCell
}

我如何格式化intArray,以便它以格式化时间 (HH:MM:SS) 的形式打印到日志和 UI,就像我使用 打印到日志中的 for loop 一样字符串格式化程序?

非常感谢任何帮助!

【问题讨论】:

    标签: arrays string swift nsdate nsdateformatter


    【解决方案1】:

    您需要创建一个函数,它将秒转换为格式化字符串,如

    func formattedTime(seconds: Int = 0) -> String {
            let hours = seconds/3600
            let minsec = seconds%3600
            let minutes = minsec / 60
            let seconds = minsec % 60
            return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
    }
    

    一旦你有了这个方法,你就可以在你的countDown方法中使用这个方法以及cellForRowAtIndexPath

    func countDown() {
        //timerInt is an array where I'm storing the Int values.
        for i in 0 ..< timerInt.count {
            print(formattedTime(timerInt[i]))
            timerInt[i]--
            print(self.timerInt[i])
        }
    }
    

    cellForRowAtIndexPath 内,您有timerInt 作为Int 数组,其中每个索引值都需要显示在单元格UILabel

     override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
            let myCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! cell
    
    
         //This is the first item i'm posting on a UILabel and it works fine.
            myCell.productName.text = productName[indexPath.row]
    
                /*This cell/label I'm unable to format like in the for loop 
                  which is formatted as a string*/
    
                 myCell.secondLabel.text = ("\(intArray[indePath.row])")
    
                 /*how do I format the intArray here so that the time 
                 */appears HH:MM:SS??
            print(self.formattedTime(self.intArray[indePath.row]))
            return myCell
        }
    

    【讨论】:

    • 感谢您的回答。我在cellForRowAtIndexPathmyCell.secondLabel.text = ("\(intArray[indexPath.row])")print(self.formattedTime(self.intArray[indexPath.row])) 的这两行中遇到错误,错误是在展开可选值时存在 nil。看起来很奇怪,无法摆脱它......
    • @rinyfo4,错误请参考this
    【解决方案2】:

    在@vacawama 的大力帮助下,这最终为我工作:

    1. 这就是我查询日期的方式,格式化日期将如何存储在数组中,然后将其放入名为intArray 的数组中。

      var createdAt = object.createdAt 如果 createdAt != nil {

                  let calendar = NSCalendar.currentCalendar()
                  let comps = calendar.components([.Hour, .Minute, .Second], fromDate: createdAt as NSDate!)
                  let hour = comps.hour  * 3600
                  let minute = comps.minute * 60
                  let seconds = comps.second
      
      
                  self.timerInt.append(hour + minute + seconds)
      
      
              }
      
      
              }
      
          }
      
      
           var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("countDown"), userInfo: nil, repeats: true)
      
      })
      self.tableView.reloadData()
      

      }

    2. 其次,我确保将 timer 变量保留在查询之外,以便计时器不会根据我正在查询的对象数倒计时。

    3. 我的 countDown 函数完成了所有的格式化:

      func countDown() {
      
          //timerInt is an array where I'm storing the Int values.
          for i in 0 ..< timerInt.count {
      
              let hours = timerInt[i] / 3600
              let minsec = timerInt[i] % 3600
              let minutes = minsec / 60
              let seconds = minsec % 60
         print(String(format: "%02d:%02d:%02d", hours, minutes, seconds))
            timerInt[i]--
              self.tableView.reloadData()
      
          }
      

      }

    4. cellForRowAtIndexPath函数中,我根据数组intArray格式化了标签在UI上的显示方式,如下所示:

         override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
          let myCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! cell
      
         //Formatting how the cell will be presented
          let hours = timerInt[indexPath.row] / 3600
          let minsec = timerInt[indexPath.row] % 3600
          let minutes = minsec / 60
          let seconds = minsec % 60
      
      
        myCell.secondLabel.text = String(format: "%02d:%02d:%02d", hours, minutes, seconds)
      
          }
      

    一切都完美无缺,并按需要显示:HH:MM:SS。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-30
      • 2012-05-31
      • 2016-01-27
      • 2017-04-04
      • 1970-01-01
      • 2021-05-10
      • 2017-07-16
      • 1970-01-01
      相关资源
      最近更新 更多