ios - Set limit to draggable item in Swift -
i have 1 imageview , textfield on image. make textfield draggable below code can draggable anywhere in screen. want textfield draggable in limit of imageview. if uncomment if check in draagedview function, textfield stuck @ left side of imageview because x values become same.
i found solution can't modify work on project. use uipangesturerecognizer drag uiview inside limited area
override func viewdidload() { super.viewdidload() // additional setup after loading view, typically nib. let gesture = uipangesturerecognizer(target: self, action: #selector(viewcontroller.draggedview(_:))) bottomtextfield.addgesturerecognizer(gesture) bottomtextfield.isuserinteractionenabled = true } func userdragged(gesture: uipangesturerecognizer){ let loc = gesture.location(in: self.view) self.bottomtextfield.center = loc } func draggedview(_ sender:uipangesturerecognizer) { let compare = myimageview.frame.maxx <= bottomtextfield.frame.maxx //if(myimageview.frame.minx <= bottomtextfield.frame.minx && compare ) // { self.view.bringsubview(tofront: sender.view!) let translation = sender.translation(in: self.view) sender.view!.center = cgpoint(x: sender.view!.center.x + translation.x, y: sender.view!.center.y + translation.y) sender.settranslation(cgpoint.zero, in: self.view) // } }
the main problem checking position before translation. means text field ends in invalid position, after if
block never reached.
this different way approach problem , means text field reaches right edges of limit:
func draggedview(_ sender: uipangesturerecognizer) { guard let senderview = sender.view else { return } var translation = sender.translation(in: view) translation.x = max(translation.x, myimageview.frame.minx - bottomtextfield.frame.minx) translation.x = min(translation.x, myimageview.frame.maxx - bottomtextfield.frame.maxx) translation.y = max(translation.y, myimageview.frame.miny - bottomtextfield.frame.miny) translation.y = min(translation.y, myimageview.frame.maxy - bottomtextfield.frame.maxy) senderview.center = cgpoint(x: senderview.center.x + translation.x, y: senderview.center.y + translation.y) sender.settranslation(.zero, in: view) view.bringsubview(tofront: senderview) }
i have made bit safer adding guard
statement @ top , removing force unwraps.
Comments
Post a Comment