Ios 阻止UIView离开屏幕
我有一个圆形的视图。这就是应用程序的全部功能-我可以使用Ios 阻止UIView离开屏幕,ios,swift,uipangesturerecognizer,Ios,Swift,Uipangesturerecognizer,我有一个圆形的视图。这就是应用程序的全部功能-我可以使用ui搜索识别器在屏幕上移动圆圈。现在我不希望我的圆圈被拖离屏幕。例如,如果我向右拖动圆,当右边缘碰到窗口边缘时,它应该停止移动圆 这是我的密码: switch rec.state { case .Began: x = fingerLocation.x - (myView?.center.x)! y = fingerLocation.y - (myView?.center.y)
ui搜索识别器在屏幕上移动圆圈。
现在我不希望我的圆圈被拖离屏幕。例如,如果我向右拖动圆,当右边缘碰到窗口边缘时,它应该停止移动圆
这是我的密码:
switch rec.state {
case .Began:
x = fingerLocation.x - (myView?.center.x)!
y = fingerLocation.y - (myView?.center.y)!
break
case .Changed:
myView?.center.x = fingerLocation.x - x
myView?.center.y = fingerLocation.y - y
if (myView?.center.x)! + (myView!.bounds.width/2) >= view.bounds.width {
myView?.center.x = view.bounds.width - myView!.bounds.width/2
}
break
case .Ended:
myView?.center = CGPointMake(fingerLocation.x - x, fingerLocation.y - y)
break
}
如果我将圆缓慢地向边缘拖动,则此代码有效。如果我快速拖动,圆圈将越过边缘,然后跳回视图,直到另一个。已更改的状态被发送如何阻止圆圈越过边缘?您可以先检查手指位置是否会导致屏幕外视图,
并且仅当视图不会移到屏幕外时才移动视图
case .Changed:
let currentRightEdge = CGRectGetMaxX(myView!.frame)
let potentialRightEdge = currentRightEdge + fingerLocation.x - x
if potentialRightEdge >= view.bounds.width {
myView?.center.x = view.bounds.width - myView!.bounds.width/2
}
else {
myView?.center.x = potentialRightEdge
}
myView?.center.y = fingerLocation.y - y
此外,我认为您不需要Swift中的中断
;-) 问题可能是,如果视图脱离屏幕,您将myView?.center.x
设置两次。试试这个:
case .Changed:
myView?.center.y = fingerLocation.y - y
var newX : Int = fingerLocation.x - x
if (newX + (myView!.bounds.width/2)) >= view.bounds.width {
myView?.center.x = view.bounds.width - myView!.bounds.width/2
} else {
myView?.center.x = newX
}
break
试着这样做:
case .Changed:
var targetX = fingerLocation.x - x
if targetX < 0 {
targetX = 0
} else if targetX > CGRectGetWidth(view.bounds) {
targetX = CGRectGetWidth(view.bounds)
}
var targetY = fingerLocation.y - y
if targetY < 0 {
targetY = 0
} else if targetY > CGRectGetHeight(view.bounds) {
targetY = CGRectGetHeight(view.bounds)
}
myView?.center = CGPoint(x: targetX, y: targetY)
案例。已更改:
var targetX=fingerLocation.x-x
如果targetX<0{
targetX=0
}如果targetX>CGRectGetWidth(view.bounds),则为else{
targetX=CGRectGetWidth(view.bounds)
}
var targetY=fingerLocation.y-y
如果目标<0{
targetY=0
}如果targetY>CGRectGetHeight(view.bounds),则为else{
targetY=CGRectGetHeight(view.bounds)
}
myView?.center=CGPoint(x:targetX,y:targetY)
您想看看x
和y
是什么吗?在圆圈上有用户点击的位置<代码>x=fingerLocation.x-(myView?.center.x)!y=fingerLocation.y-(myView?.center.y)你能发一些伪代码吗?我已经做了几个小时了,没有什么进展。谢谢!你怎么能在不知道x是什么的情况下使用它呢。为了清晰起见,我把它简化了。您在代码中引入了x,但没有解释它是什么或如何计算它。我假设您知道如何使用此变量计算新位置。也许你应该把它添加到你的问题中去澄清一下。这就是我的想法。也许是我见过的最短的类范围变量;-)。所以它是在.start
中设置的,应该可以工作,对吗?