我在一个类中编写了一个struct。此结构在renderView()
方法中初始化一次。每次调用timer.pause()
函数时,变量currentTime
都设置为0.我无法弄清楚原因,结构中的变量根本不受该方法的影响。结构本身也没有被新初始化。
为什么会改变currentTime
?
这是我的代码:
//Class
override func renderView() -> UIView {
let view = super.renderView("TimeWidget")
timer = Timer()
return view
}
func currentOrientation(orientation: UIDeviceOrientation) {
if orientation != .Portrait{
timer.start({ (newTime) in
self.timeLabel.text = (self.date + newTime.seconds).toString(DateFormat.Custom("HH:mm:ss"))
})
}else{
timer.pause()
}
}
//Helper
extension TimeWidget{
struct Timer {
private var _timer: NSTimer!
private var currentTime: Int!
init(){
currentTime = 0
_timer = NSTimer()
}
mutating func start(onTimeChange: (newTime: Int)->Void){
_timer = NSTimer.every(1.0) {
self.currentTime = self.currentTime + 1
onTimeChange(newTime: self.currentTime)
}
}
func pause(){
_timer.invalidate()
}
mutating func reset(){
_timer.invalidate()
currentTime = 0
}
}
}
编辑:
从UICollectionViewCell调用 renderView()
:
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath)
//render View
cell.addSubview(widgets[indexPath.row].renderView())
//define height
cell.frame = cell.standardFrameWithHeight(widgets[indexPath.row].height)
return cell
}