按下每个按钮生成新单元格

时间:2015-12-14 23:33:23

标签: ios swift uitableview

这里是Swift 2的新手,我有一个简单的问题。还没有找到任何相关的答案,但我试图让表格视图单元格每次按下一圈按钮时生成一个单元格(类似于苹果秒表)。我遇到的问题是如何将我的cellContent数组项目转移到表格视图中的单个单元格中。提前谢谢!

var startTime = NSTimeInterval()
var timer = NSTimer()
var cellContent:[String] = []

func updateTime() {

    let currentTime = NSDate.timeIntervalSinceReferenceDate()

    //Find the difference between current time and start time.

    var elapsedTime: NSTimeInterval = currentTime - startTime

    //calculate the minutes in elapsed time.

    let minutes = UInt8(elapsedTime / 60.0)

    elapsedTime -= (NSTimeInterval(minutes) * 60)

    //calculate the seconds in elapsed time.

    let seconds = UInt8(elapsedTime)

    elapsedTime -= NSTimeInterval(seconds)

    //find out the fraction of milliseconds to be displayed.

    let fraction = UInt8(elapsedTime * 100)

    //add the leading zero for minutes, seconds and millseconds and store them as string constants

    let strMinutes = String(format: "%02d", minutes)
    let strSeconds = String(format: "%02d", seconds)
    let strFraction = String(format: "%02d", fraction)

    //concatenate minuets, seconds and milliseconds as assign it to the UILabel

    timeDisplay.text = "\(strMinutes)"+":"+"\(strSeconds)"+":"+"\(strFraction)"

} //changes time on display

@IBAction func lapButton(sender: AnyObject) //adds time to array
{
    cellContent.append(timeDisplay.text!)
}

@IBAction func pause(sender: AnyObject) {

    timer.invalidate()
} //pauses timer

@IBAction func stop(sender: AnyObject) {

    timer.invalidate()
    timeDisplay.text = "00:00:00"

} //stops timer

@IBAction func play(sender: AnyObject) {

    if !timer.valid
    {
        timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true)
        startTime = NSDate.timeIntervalSinceReferenceDate()
    }

} //starts timer if inactive

@IBOutlet var timeDisplay: UILabel!

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    return cellContent.count //need to revise
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{

    let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
    cell.textLabel?.text = cellContent[indexPath.row] //need to revise

    return cell
}

2 个答案:

答案 0 :(得分:1)

我对回答感到有点紧张,因为看起来我的问题解决方案很简单,一定是错的,但无论如何我都会试一试。

我认为在您的lapButton功能中,您需要调用UITableView reloadData()函数描述here。正如你所看到的那样,你可以重新加载表格,比如添加动画等等。

我希望这有帮助!

P.S。你的UITableView在哪里?我实际上并没有在你的代码中看到对它的引用。

答案 1 :(得分:1)

您应该通知UITableView数据源数据已更改,并且表视图必须更新单元格和可见单元格的总数。

最简单的方法是致电reloadData

@IBAction func lapButton(sender: AnyObject) //adds time to array
{
    cellContent.append(timeDisplay.text!)
    yourTableView.reloadData()
}

但更有效的方法是使用insertRowsAtIndexPaths: animation: