【发布时间】:2015-04-16 17:42:34
【问题描述】:
我正在尝试创建一个倒计时应用程序,该应用程序将显示年数......距离即将到来的日期还有几秒钟。我希望能够在表格视图中查看几个倒计时。我有一些独立于表格视图单元格来创建倒计时的基本逻辑:
.
.
.
var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "countdown", userInfo: nil, repeats: true)
func countdown() {
let hourMinuteComponents: NSCalendarUnit =
NSCalendarUnit.CalendarUnitYear |
NSCalendarUnit.CalendarUnitMonth |
NSCalendarUnit.CalendarUnitDay |
NSCalendarUnit.CalendarUnitHour |
NSCalendarUnit.CalendarUnitMinute |
NSCalendarUnit.CalendarUnitSecond
let timeDifference = userCalendar.components(
hourMinuteComponents,
fromDate: NSDate(),
toDate: date1.enteredDate as NSDate,
options: nil)
// Sample Output
println("Year: \(timeDifference.year)")
println("Month: \(timeDifference.month)")
println("Day: \(timeDifference.day)")
println("Hour: \(timeDifference.hour)")
println("Minute: \(timeDifference.minute)")
println("Second: \(timeDifference.second)")
}
这很好用,控制台显示倒计时。但是,当我尝试从单元格调用它时,我无法克服错误。
由于未捕获的异常而终止应用程序 'NSInvalidArgumentException',原因:'-[__NSCFTimer 行]: 无法识别的选择器发送到实例
这是无效的代码。
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
println("Index Path: \(indexPath)")
let cell = tableView.dequeueReusableCellWithIdentifier("countDownCell") as! UITableViewCell
let cellIndex = indexPath
var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "update:", userInfo: cellIndex, repeats: true)
//let secondlabel = cell.viewWithTag(1005) as! UILabel
//secondlabel.text = "Test"
return cell
}
func update(cellIndex: NSIndexPath) {
let hourMinuteComponents: NSCalendarUnit =
NSCalendarUnit.CalendarUnitYear |
NSCalendarUnit.CalendarUnitMonth |
NSCalendarUnit.CalendarUnitDay |
NSCalendarUnit.CalendarUnitHour |
NSCalendarUnit.CalendarUnitMinute |
NSCalendarUnit.CalendarUnitSecond
let timeDifference = userCalendar.components(
hourMinuteComponents,
fromDate: NSDate(),
toDate: date1.enteredDate as NSDate,
options: nil)
println("Year: \(timeDifference.year)")
println("Month: \(timeDifference.month)")
println("Day: \(timeDifference.day)")
println("Hour: \(timeDifference.hour)")
println("Minute: \(timeDifference.minute)")
println("Second: \(timeDifference.second)")
if let cell = tableView.cellForRowAtIndexPath(cellIndex) {
let yearlabel = cell.viewWithTag(1000) as! UILabel
let secondlabel = cell.viewWithTag(1005) as! UILabel!
}
secondlabel.text = "\(timeDifference.second)"
}
感谢您提供的任何帮助。我最初将我的修复尝试集中在更改我从计时器调用 update() 的方式上。我尝试显式传递单元格,然后认为尝试调用单元格的 indexPath 会更好。我还按照许多 NSTimer 帖子中的建议检查了我的语法。我认为我做对了(并且相信我已经尝试了几乎所有其他选项)。
代码在这一行中断:
if let cell = tableView.cellForRowAtIndexPath(cellIndex) { ...
【问题讨论】:
标签: ios uitableview swift nstimer