【发布时间】:2018-02-05 10:01:28
【问题描述】:
我想通过触摸图像来移动 UIView。
我在UIImageView 和touchesBegan 中计算了图像的CGRect,touchesMoved 函数可以移动视图。
我在这些函数中有一个for 循环(touch in touches),在这个循环中有通过触摸移动视图的代码。
我只想在视图位于图像本身上方时才移动视图,因此我将 if 放入 for 循环中,这是下一个循环:
if imageRect.contains(selectedText.frame)
问题是当我将视图移出 imageRect 时,它卡住了。 我不能把它移回来。 我希望能够将 UIView 移动到图像的 CGRect 内,但不能移出。
编辑:
selectedText 是 UIView,在 touchesBegan 函数中我创建了变量 toucheLocation(我在 touchesMoved 函数中有相同的代码,除了 var toucheLocation = location 部分)
if selectedText.frame.contains(toucheLocation){
selectedText.center.x = selectedText.center.x + (location.x - toucheLocation.x)
selectedText.center.y = selectedText.center.y + (location.y - toucheLocation.y)
toucheLocation = location
}
编辑2:
这是代码的较大部分:
(var toucheLocation = CGPoint() 部分在课程的开头)
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: imageView)
toucheLocation = location
if imageRect.contains(selectedText.frame){
if selectedText.frame.contains(toucheLocation){
selectedText.center.x = selectedText.center.x + (location.x - toucheLocation.x)
selectedText.center.y = selectedText.center.y + (location.y - toucheLocation.y)
toucheLocation = location
}
}
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: imageView)
if imageRect.contains(selectedText.frame){
if selectedText.frame.contains(toucheLocation){
selectedText.center.x = selectedText.center.x + (location.x - toucheLocation.x)
selectedText.center.y = selectedText.center.y + (location.y - toucheLocation.y)
toucheLocation = location
}
}
}
}
【问题讨论】:
-
你能告诉我touchesBegan func吗?你在这做了什么
-
@Dominik 你的问题下面有一个编辑按钮,用它来包含所有相关代码
-
@Dominik ALL 相关代码..在编辑上方有这一行
if imageRect.contains(selectedText.frame),但在添加的代码中我看不到它..
标签: ios swift xcode uiview uiimageview