简体   繁体   English

只要用户触摸CGRect,如何使它在屏幕上随机移动?

[英]How can I make a CGRect move randomly around the screen so long as the user is touching it?

I'd like for a rectangle move to move around the screen randomly when the user holds his/her finger on it, and stop moving if the user's finger moves off of it. 我想让矩形移动在用户将手指放在屏幕上时在屏幕上随机移动,并在用户的手指离开屏幕时停止移动。 In other words, so long as the user is able to keep up with it, it will keep moving. 换句话说,只要用户能够跟上它,它就会一直运动。 How should I go about doing this? 我应该怎么做呢?

let rect = CGRect(x: 157, y: 398, width: 100, height: 100) // create rect
let view = UIView(frame: rect) // create view for rect
view.backgroundColor = .red // color rect
self.view.addSubview(view) // display rect

Simply you can use touch Methods to move your view 只需使用触摸方法即可移动视图

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first as! UITouch
    let location = touch.location(in: self.view) //Gives you CGPoints
    YourView.frame = CGRect(origin: location, size: Your size here>
}

That might help! 这可能会有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM