【问题标题】:Swift NSTimer retrieving userInfo as CGPointSwift NSTimer 将 userInfo 检索为 CGPoint
【发布时间】:2014-11-25 17:40:05
【问题描述】:
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    let touch = touches.anyObject() as UITouch
    let touchLocation = touch.locationInNode(self)

    timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "shoot", userInfo: touchLocation, repeats: true) // error 1
}

func shoot() {
    var touchLocation: CGPoint = timer.userInfo // error 2
    println("running")
}

我正在尝试创建一个定期运行的计时器,将触摸点 (CGPoint) 作为 userInfo 传递给 NSTimer,然后在 shoot() 函数中访问它。但是,现在我收到一个错误提示

1) 调用中的额外参数选择器

2) 无法转换表达式类型 AnyObject?到CGPoint

现在我似乎无法将 userInfo 传递给其他函数然后检索它。

【问题讨论】:

    标签: ios swift nstimer userinfo


    【解决方案1】:

    不幸的是,CGPoint 不是对象(至少在 Cocoa API 起源的 Objective-C 世界中)。它必须包装在 NSValue 对象中才能放入集合中。

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        let touch = touches.anyObject() as UITouch
        let touchLocation = touch.locationInNode(self)
        let wrappedLocation = NSValue(CGPoint: touchLocation)
    
        timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "shoot:", userInfo: ["touchLocation" : wrappedLocation], repeats: true)
    }
    
    func shoot(timer: NSTimer) {
        let userInfo = timer.userInfo as Dictionary<String, AnyObject>
        var touchLocation: CGPoint = (userInfo["touchLocation"] as NSValue).CGPointValue()
        println("running")
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    相关资源
    最近更新 更多