可拖动的UIView Swift 3

raogr8fs  于 2023-02-15  发布在  Swift
关注(0)|答案(4)|浏览(225)

我希望能够拖动屏幕上的对象,但它们不会。我试了所有方法,但仍然不能。
下面是代码。

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")
    }
}

它们也有重力。形状是正方形和圆形。
说明:in. begin-我禁用所选表格的重力。in. changed-我尝试更改坐标。in. end-我再次启用重力。
截图。

aiqt4smr

aiqt4smr1#

步骤1:选择一个视图,将其拖到故事板中。

@IBOutlet weak var viewDrag: UIView!

**步骤2:**添加PanGesture。

var panGesture       = UIPanGestureRecognizer()

**步骤3:**在ViewDidLoad中添加以下代码。

override func viewDidLoad() {
    super.viewDidLoad()

    panGesture = UIPanGestureRecognizer(target: self, action: #selector(ViewController.draggedView(_:)))
    viewDrag.isUserInteractionEnabled = true
    viewDrag.addGestureRecognizer(panGesture)

}

**步骤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)
}

**步骤5:**输出。

pvabu6sv

pvabu6sv2#

一月一日

    • 第1步:从情节提要中选取一个UIView,将其拖动到ViewController文件中并创建UIView的IBOutlet。**
@IBOutlet weak var viewDrag: UIView!
var panGesture = UIPanGestureRecognizer()
    • 步骤2:在viewDidLoad()中添加以下代码。**
override func viewDidLoad() {
super.viewDidLoad()
  let panGesture = UIPanGestureRecognizer(target: self, action:(Selector(("draggedView:"))))
  viewDrag.isUserInteractionEnabled = true
  viewDrag.addGestureRecognizer(panGesture)
}
    • 第3步:创建func并添加代码来移动UIView,如下所示。**
func draggedView(sender:UIPanGestureRecognizer){
    self.view.bringSubviewToFront(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)
}

希望这能对人有所帮助。

ecr0jaav

ecr0jaav3#

如果你子类化一个视图,这是非常容易的:

可拖动视图...

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)
    }
}

1.将UIView拖放到场景中。
1.通常,从左侧(即x位置)添加约束,从顶部(即y位置)添加约束。
1.在故事板中,只需简单地命名约束"fromleft"和"fromtop"

你完了。
它现在工作得很好-就是这样。

那个方便的constraint(调用是什么?

请注意,视图只是通过名称找到自己的约束。
在Xcode中,仍然没有办法使用IBOutlets这样的约束。幸运的是,通过"标识符"找到它们非常容易。(事实上,这正是.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({ $0.constraints }).filter { c in
            return c.firstItem as? UIView == self ||
                c.secondItem as? UIView == self
        }
    }

尖端...边缘对中心!

不要忘记在视图上设置约束(如上图所示):
您可以将左边的设置为:

  • 到白框的"左边缘",或
  • 到白色盒子的"中心"。

根据你的情况选择一个合适的。它会让你更容易计算,设置滑块等。
脚注-"初始化" UI视图、UI "I"视图、

// UI "I" View ... "I" for initializing
// Simply saves you typing inits everywhere
import UIKit
class UIIView: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        common()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        common()
    }
    func common() { }
}
rdrgkggo

rdrgkggo4#

此UIView扩展使UIView对象可拖动,并将移动限制在屏幕范围内。

extension UIView {
    func makeDraggable() {
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:)))
        self.addGestureRecognizer(panGesture)
    }
    
    @objc func handlePan(_ gesture: UIPanGestureRecognizer) {
        guard gesture.view != nil else { return }
        
        let translation = gesture.translation(in: gesture.view?.superview)
        
        var newX = gesture.view!.center.x + translation.x
        var newY = gesture.view!.center.y + translation.y
        
        let halfWidth = gesture.view!.bounds.width / 2.0
        let halfHeight = gesture.view!.bounds.height / 2.0
        
        // Limit the movement to stay within the bounds of the screen
        newX = max(halfWidth, newX)
        newX = min(UIScreen.main.bounds.width - halfWidth, newX)
        newY = max(halfHeight, newY)
        newY = min(UIScreen.main.bounds.height - halfHeight, newY)
        
        gesture.view?.center = CGPoint(x: newX, y: newY)
        gesture.setTranslation(CGPoint.zero, in: gesture.view?.superview)
    }
}

相关问题