如何在快速UIView中获取随机坐标?



我正在创建一个动画函数,以便在uiView中随机生成imageViews。然而,它总是返回 0,0 请帮助!

private func coinAnimation(image: UIImage) {
let imageView = UIImageView(image: image)
imageView.frame = self.view.convert(self.coinsView.frame, from: self.coinsView.superview!)
imageView.contentMode = UIView.ContentMode.scaleAspectFit
imageView.backgroundColor = .red
let frame = coinsView.frame
let x = randomInRange(lo: 0, hi: Int(frame.size.width - imageView.bounds.size.width))
let y = randomInRange(lo: 0, hi: Int(frame.size.height - imageView.bounds.size.height))
let position = CGPoint(x: x, y: y)
UIView.animate(withDuration: 1.0, delay: 0.0, options: .curveEaseInOut, animations: {
imageView.center = position
self.coinsView.addSubview(imageView)
}, completion: nil)
}
private func randomInRange(lo: Int, hi : Int) -> Int {
return lo + Int(arc4random_uniform(UInt32(hi - lo + 1)))
}

您的问题与以下行有关

imageView.frame = self.view.convert(self.coinsView.frame, from: self.coinsView.superview!)

此行将相同的coinsView帧设置为imageView。当您尝试在下面的代码中获取随机 x 和 y 点时,它将始终返回 0。因为frame.size.widthimageView.bounds.size.width是一样的,同样是高度。

let x = randomInRange(lo: 0, hi: Int(frame.size.width - imageView.bounds.size.width))
let y = randomInRange(lo: 0, hi: Int(frame.size.height - imageView.bounds.size.height))

为了更好地理解,在代码中添加以下行以设置imageView框架,您需要首先将静态框架设置为图像视图。

imageView.frame = CGRect(x: 0, y: 0, width: 30, height: 30)

确保宽度和高度应小于硬币的宽度和高度查看的宽度和高度

最新更新