ios 可拖动的 UIView Swift 3
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43714948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Draggable UIView Swift 3
提问by Dpetrov
I want to be able to drag the objects on the screen, but they wont. I tried everything but still cant.
我希望能够拖动屏幕上的对象,但它们不会。我尝试了一切,但仍然不能。
Here are the code.
这是代码。
func panGesture(gesture: UIPanGestureRecognizer) {
switch gesture.state {
case .began:
print("Began.")
for i in 0..<forms.count {
if forms[i].frame.contains(gesture.location(in: view)) {
gravity.removeItem(forms[i])
}
}
case .changed:
let translation = gesture.translation(in: forms[1])
gesture.view!.center = CGPoint(x: gesture.view!.center.x + translation.x, y: gesture.view!.center.y + translation.y)
gesture.setTranslation(CGPoint.zero, in: self.view)
print("\(gesture.view!.center.x)=\(gesture.view!.center.y)")
print("t;: \(translation)")
case .ended:
for i in 0..<forms.count {
if forms[i].frame.contains(gesture.location(in: view)) {
gravity.addItem(forms[i])
}
}
print("Ended.")
case .cancelled:
print("Cancelled")
default:
print("Default")
}
}
Also they have gravity. The forms are squares and circles.
他们也有重力。形式是正方形和圆形。
Explanation: in .began - i disable the gravity for selected form. in .changed - i try to change the coordinates. in .end - i enable again gravity.
说明:在 .began 中 - 我禁用所选形式的重力。在 .changed - 我尝试更改坐标。在 .end - 我再次启用重力。
ScreenShot.
截屏。
回答by Kirit Modi
Step 1: Take one View which you want to drag in storyBoard.
第 1 步:在 storyBoard 中选择一个你想拖拽的 View。
@IBOutlet weak var viewDrag: UIView!
Step 2 :Add PanGesture.
第 2 步:添加 PanGesture。
var panGesture = UIPanGestureRecognizer()
Step 3 :In ViewDidLoad adding the below code.
第 3 步:在 ViewDidLoad 中添加以下代码。
override func viewDidLoad() {
super.viewDidLoad()
panGesture = UIPanGestureRecognizer(target: self, action: #selector(ViewController.draggedView(_:)))
viewDrag.isUserInteractionEnabled = true
viewDrag.addGestureRecognizer(panGesture)
}
Step 4 :Code for draggedView.
第 4 步:draggedView 的代码。
func draggedView(_ sender:UIPanGestureRecognizer){
self.view.bringSubview(toFront: viewDrag)
let translation = sender.translation(in: self.view)
viewDrag.center = CGPoint(x: viewDrag.center.x + translation.x, y: viewDrag.center.y + translation.y)
sender.setTranslation(CGPoint.zero, in: self.view)
}
Step 5 :Output.
第 5 步:输出。
回答by Dilip Tiwari
Use below code for Swift 2.3
对 Swift 2.3 使用以下代码
@IBOutlet weak var viewDrag: UIView!
var panGesture = UIPanGestureRecognizer()
In ViewDidLoad adding the below code.
在 ViewDidLoad 中添加以下代码。
override func viewDidLoad() {
super.viewDidLoad()
var panGesture = UIPanGestureRecognizer(target: self, action:("draggedView:"))
viewDrag.userInteractionEnabled = true
viewDrag.addGestureRecognizer(panGesture)
}
func draggedView(sender:UIPanGestureRecognizer){
self.view.bringSubviewToFront(viewDrag)
let translation = sender.translationInView(self.view)
viewDrag.center = CGPoint(x: viewDrag.center.x + translation.x, y: viewDrag.center.y + translation.y)
sender.setTranslation(CGPoint.zeroPoint, inView: self.view)
}
Hope this will help someone.
希望这会帮助某人。
回答by Fattie
It's very easy if you subclass a view:
如果您对视图进行子类化,这很容易:
I like to just use a view like this:
我喜欢使用这样的视图:
class DraggableView: UIIView {
var fromleft: NSLayoutConstraint!
var fromtop: NSLayoutConstraint!
override func didMoveToWindow() {
super.didMoveToWindow()
if window != nil {
fromleft = constraint(id: "fromleft")!
fromtop = constraint(id: "fromtop")!
}
}
override func common() {
super.common()
let p = UIPanGestureRecognizer(
target: self, action: #selector(drag))
addGestureRecognizer(p)
}
@objc func drag(_ s:UIPanGestureRecognizer) {
let t = s.translation(in: self.superview)
fromleft.constant = fromleft.constant + t.x
fromtop.constant = fromtop.constant + t.y
s.setTranslation(CGPoint.zero, in: self.superview)
}
}
drop a UIView in to your scene. make it any size you wish using constraints
as you normally would, add a constraint from the left (that's the x position) and add a constraint from the top (that's the y position)
in storyboard simply simply name the constraints "fromleft" and "fromtop"
将 UIView 放入您的场景中。使用约束使其成为您希望的任何大小
像往常一样,从左侧添加约束(即 x 位置)并从顶部添加约束(即 y 位置)
在故事板中,只需简单地将约束命名为“fromleft”和“fromtop”
You're done - it works perfectly, end.
你已经完成了 - 它完美地工作,结束。
Note that, of course, you may add some limits in drag
to keep the movement within a box or whatever is relevant to you.
请注意,当然,您可以添加一些限制drag
以将移动保持在框内或与您相关的任何内容中。
The above code will work perfectly for full-screen draggingwith no further code.
上面的代码可以完美地用于全屏拖动,无需进一步的代码。
That handy constraint(
call...
那个方便的constraint(
电话...
Notice the view simply finds it's own constraints by name.
请注意,视图只是通过名称找到它自己的约束。
In any real-world autolayout project, you need to get constraints to use them in code.
在任何现实世界的自动布局项目中,您都需要获得约束才能在代码中使用它们。
Incredibly, in Xcode there is STILL no way to just drag constraints to IBOutlets or use some similar mechanism. (As of 2020.)
令人难以置信的是,在 Xcode 中仍然无法将约束拖动到 IBOutlets 或使用一些类似的机制。(截至 2020 年。)
Fortunately it is very easy to find them by "identifier".
幸运的是,通过“标识符”很容易找到它们。
(Indeed this is the very purpose of the .identifier on constraints.)
(事实上,这正是 .identifier 在约束上的目的。)
extension UIView {
func constraint(id: String) -> NSLayoutConstraint? {
let cc = self.allConstraints()
for c in cc { if c.identifier == id { return c } }
//print("someone forgot to label constraint \(id)") //heh!
return nil
}
func allConstraints() -> [NSLayoutConstraint] {
var views = [self]
var view = self
while let superview = view.superview {
views.append(superview)
view = superview
}
return views.flatMap({ ##代码##.constraints }).filter { c in
return c.firstItem as? UIView == self ||
c.secondItem as? UIView == self
}
}
Tip...
提示...
Don't forget when you make the constraints on a view (as in the image above) you can set the left one say to be either to the left edgeof the white box or to the centerof the white box. Choosing the correct one will make it much easier to do calculations, set sliders etc.
不要忘记在对视图进行约束时(如上图所示),您可以将左侧设置为白框的左边缘或白框的中心。选择正确的一个将使计算、设置滑块等变得更加容易。