swift - How do I move an object back and forth with touch in iOS -
i need move image , forth based on user's finger. want able touch screen , image move towards touch. image should move left right not , down , add limits how far image can go towards 1 side of screen.
i know sounds lot have tried many things of have caused problems. first time able click , drag image when clicked somewhere else image appear there wouldn't move there appeared.
the second thing tried allowed me drag image when clicked out of image wouldn't move towards finger @ all. @ point i'm frustrated , appreciate help. here code.
import uikit class viewcontroller: uiviewcontroller { @iboutlet var person: uiimageview! override func viewdidload() { super.viewdidload() } override func touchesbegan(touches: set<uitouch>, withevent event: uievent?) { touch in (touches ){ let location = touch.locationinview(self.view) if person.frame.contains(location){ person.center = location } } } override func touchesmoved(touches: set<uitouch>, withevent event: uievent?) { touch in (touches ){ let location = touch.locationinview(self.view) if person.frame.contains(location){ person.center = location } } } override func didreceivememorywarning() { super.didreceivememorywarning() // dispose of resources can recreated. } }
i assume you're using touchesbegan(_:withevent:) , touchesmoved(_:withevent:) touch events. these methods give uitouch can convert cgpoint using locationinview(_:).
when touch begins (i.e. touchesbegan(_:withevent:)), should animate custom view cgpoint of touch. e.g.:
uiview.animatewithduration(0.3, animations: { // adjust x, not y, restrict movement along x-axis. // check x value of point see if reached limit. self.squareview.frame.origin.x = point.x }) when touch moves (i.e. touchesmoved(_:withevent:)), should set custom view's location cgpoint of new touch. e.g.:
// adjust x, not y, restrict movement along x-axis. // check x value of point see if reached limit. squareview.frame.origin.x = point.x some suggestions
- only use first
uitouchset of touches, can rid of for-loop. - the line
if person.frame.contains(location){wrong because movingpersonif touch withinperson's frame, remove , set frame's originuitouch's point (or animate using code above).
Comments
Post a Comment