Swift 4:防止UIView的子视图移动到它的父节点之外
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Swift 4:防止UIView的子视图移动到它的父节点之外相关的知识,希望对你有一定的参考价值。
我有一个UIView
和一个半尺寸的SubView。用户可以在主视图周围移动子视图,这就是我想要的,但问题是,当用户将UIView
拖到MainView
的角落时,子视图消失并进入其下方的父视图,
Main UIView
尺寸:105x105
SubView
尺寸:35x35
请看一下这个样本
我想锁定子视图移动到MainView
之外,我通过以下代码实现了拖动:
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch : UITouch = touches.first!
self.subview.center = touch.location(in: imageview) // here
if touch.view == self.imageview {
if touch.location(in: view).x >= 245 {
self.rotateMe.transform = CGAffineTransform(rotationAngle: 1)
} else {
self.rotateMe.transform = CGAffineTransform(rotationAngle: -1)
}
}
}
但我无法锁定子视图。
答案
尝试这一点必须适合您的要求
import UIKit
class DraggableView: UIView {
var localTouchPosition : CGPoint?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
let touch = touches.first
self.localTouchPosition = touch?.preciseLocation(in: self)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
let touch = touches.first
guard let location = touch?.location(in: self.superview), let localTouchPosition = self.localTouchPosition else{
return
}
let origin = CGPoint(x: location.x - localTouchPosition.x, y: location.y - localTouchPosition.y)
if(origin.x >= 0 && origin.y >= 0){
if(origin.x + self.bounds.size.width <= self.superview!.bounds.size.width && origin.y + self.bounds.size.height <= self.superview!.bounds.size.height)
{
self.frame.origin = origin
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
self.localTouchPosition = nil
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesCancelled(touches, with: event)
self.localTouchPosition = nil
}
}
另一答案
这个答案 将这些条件放在父视图及其子视图中
if (subview.origin.y + subview.size.height) > parentview.height {
subview.origin.y = parentview.size.height - subview.size.height
}
if (subview.origin.x + subview.size.width) > parentview.width {
subview.origin.x = parentview.size.width - subview.size.width
}
if (subview.origin.x < 0) {
subview.origin.x = 0
}
if (subview.origin.y < 0) {
subview.origin.y = 0
}
以上是关于Swift 4:防止UIView的子视图移动到它的父节点之外的主要内容,如果未能解决你的问题,请参考以下文章
无法设置 UIView 的 backgroundColor,它是 Swift 中 UIScrollView 的子视图
swift 以编程方式将UIScrollView滚动到Swift中的子UIView(子视图)的顶部