UIimages move to the center when going to another view

余生颓废 提交于 2019-12-03 21:20:53

Your drag and drop code is manually configuring the layout by mutating the view.center property.

Once auto layout is enabled, auto layout takes responsibility for setting up the layout, so it takes exclusive responsibility for setting view.center, view.bounds, and view.frame (which is actually just calculated from center and bounds).

So once auto layout is enabled, although you can still set view.center manually, auto layout will clobber whatever you do the next time it calculates the layout that satisfies the constraints you have in place.

So how do you update your code to work with auto layout? If you want to use auto layout, what you need to do is modify your handlePan: method so that instead of modifying view.center it modifies whichever auto layout constraint is being used to calculate view.center. The details of this will depend on your constraint configuration. But if we assume, for example, that there is an NSLayoutContraint topSpaceConstraint that sets the view's top space to the superview, and another NSLayoutConstraint leftSpaceConstraint that sets the view's left space to the superview, then you could produce the same effect as

view.center = CGPointMake(view.center.x + translation.x,
                          view.center.y+ translation.y);

by instead doing something like

topSpaceConstraint.constant = topSpaceConstraint.constant + translation.y;
leftSpaceConstraint.constant = leftSpaceConstraint.consant + translation.x;
[view setNeedsLayout];
[view layoutIfNeeded];

The first two lines update the constraints. The last two lines cause the auto layout system to recalculate the resulting frame and apply it right away, rather than waiting until the next turn of the run loop.

Alternatively, you might be able to get away with updating the frame manually when you get UIGestureRecognizerChanged events, and then making the result "permanent" by updating the constraints as shown above only once you get UIGestureRecognizerEnded event. That would be more performant, since during the many UIGestureRecognizerChanged events you'd be updating the frame directly rather than relying on the auto layout system to do it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!