想知道为什么这段代码会给我错误,"无法指定类型的值'()'输入' CGPoint'"。当whiteDot覆盖smallDot时,我希望smallDot在屏幕上的随机位置产生。
class SecondViewController: UIViewController {
private var addOne = 0
func spawnRandomPosition() {
let height = self.view!.frame.height
let width = self.view!.frame.width
let randomPosition = CGPoint(x:CGFloat(arc4random()).truncatingRemainder(dividingBy: height),
y: CGFloat(arc4random()).truncatingRemainder(dividingBy: width))
return smallDot.center = randomPosition
}
@IBAction func handlePan(recognizer:UIPanGestureRecognizer) {
let translation = recognizer.translation(in: self.view)
if let view = recognizer.view {
view.center = CGPoint(x:view.center.x + translation.x,
y:view.center.y + translation.y)
}
recognizer.setTranslation(CGPoint.zero, in: self.view)
if (WhiteDot.frame.contains(smallDot.frame) && smallDot.image != nil) {
smallDot.image = nil;
addOne += 1
score.text = "\(addOne)"
smallDot.center = spawnRandomPosition() //this is line giving error//
}
}
}
答案 0 :(得分:1)
它给出错误,因为spawnRandomPosition
没有返回值。如果你修复它以返回你生成的坐标,你也可能需要将它分配给图像视图的坐标。
请参阅apple docs以了解返回函数的正确语法。 https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html
答案 1 :(得分:1)
您没有从方法返回任何值。您需要返回CGPoint
才能在handlePan:
方法中使用它。定义函数返回值CGPoint
并返回您计算的随机位置。
func spawnRandomPosition() -> CGPoint {
let height = self.view!.frame.height
let width = self.view!.frame.width
let randomPosition = CGPoint(x:CGFloat(arc4random()).truncatingRemainder(dividingBy: height),
y: CGFloat(arc4random()).truncatingRemainder(dividingBy: width))
return randomPosition
}