我设法通过平移手势阻止我的UIView走出容器,但我正在努力实现的是阻止它的边缘。目前,它直接到达最后一个像素边缘,而不是可移动视图的边缘。
我尝试更改帧值,我认为这是要走的路,但无法产生正确的结果。不知道我有多接近或者有更简单的方法吗?
//Container is self.sliderContainer
//Green Block is sender.view which has a UIGesture applied
var location = sender.locationInView(self.view)
var newFrame = CGRectMake(0, 0, self.sliderContainer.frame.width, self.sliderContainer.frame.height)
let obstacleViewFrame = self.view.convertRect(self.sliderContainer.frame, fromView: self.sliderContainer.superview)
// Check if the touch is inside the obstacle view
if CGRectContainsPoint(obstacleViewFrame, location) {
sender.view!.center.x = sender.view!.center.x + translation.x
sender.setTranslation(CGPointZero, inView: self.view)
}
答案 0 :(得分:2)
我建议以最简单的方式来做,而不是限制手势,只是确保矩形不会超出范围:
let movingView = sender.view!
let minCenterX = movingView.frame.size.width / 2
let maxCenterX = self.sliderContainer.frame.width - movingView.frame.size.width / 2
let newCenterX = movingView.center.x + translation.x
movingView.center.x = min(maxCenterX, max(minCenterX, newCenterX))
答案 1 :(得分:1)
看起来您基于触摸的坐标而不是sender.view
的框架来确定幻灯片中发件人视图的移动。
let senderViewFrame = self.view.convertRect(sender.view!.frame, fromView: sender.view!.superview)
let insetSenderViewFrame = CGRectInset(senderViewFrame, 0.0, 10.0 /*or whatever's needed*/)
let obstacleViewFrame = self.view.convertRect(self.sliderContainer.frame, fromView: self.sliderContainer.superview)
// Check if the sender view is inside the obstacle view
if CGRectContainsRect(obstacleViewFrame, insetSenderViewFrame) {
sender.view!.center.x = sender.view!.center.x + translation.x
sender.setTranslation(CGPointZero, inView: self.view)
}