简体   繁体   中英

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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