我正在制作益智游戏,我必须在UIviews
的另一个UIviews
或UIimages
上拖动多个Viewcontroller
。
以下是单个uiview可拖动的link。
在这个程序中,只有一个UIview
可以拖动,现在我想添加更多UIviews
我可以拖动。
import UIKit
class GameViewController: UIViewController, UIGestureRecognizerDelegate, UITextFieldDelegate {
@IBOutlet weak var viewDrag: UIView!
var panGesture = UIPanGestureRecognizer()
override func viewDidLoad() {
super.viewDidLoad()
panGesture = UIPanGestureRecognizer(target: self, action: #selector(GameViewController.draggedView(_:)))
viewDrag.isUserInteractionEnabled = true
viewDrag.addGestureRecognizer(panGesture)
viewDrag.backgroundColor = UIColor.green
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc 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)
}
}
以下是UIview
UIimage
上可拖动的白色方形viewcontroller
的图像
答案 0 :(得分:0)
我为你做了一个简单的例子。
在示例中,我创建了一个函数,它将创建5个可拖动的UIViews:
/// Creates A Row Of 5 Draggable UIViews
func createDraggableViews(){
//1. Determine The Size Of The Draggable View
let viewSize = CGSize(width: 50, height: 50)
//2. Create Padding Between The Views
let padding: CGFloat = 10
//2. Create 5 Draggable Views
for i in 0 ..< 5{
print((CGFloat(i) * viewSize.width) + 10)
let draggableView = UIView(frame: CGRect(x: 10 + (CGFloat(i) * viewSize.width) + (CGFloat(i) * padding), y: 100,
width: viewSize.width, height: viewSize.height))
draggableView.backgroundColor = .purple
//2a. Create A Pan Gesture Recognizer So The View Can Be Moved
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(moveObject(_:)))
draggableView.addGestureRecognizer(panGesture)
//2b. Add The Draggable View To The Main View
self.view.addSubview(draggableView)
}
}
然后可以通过以下代码使这些视图可拖动:
/// Moves A Draggable Object Around The Screen
///
/// - Parameter gesture: UIPanGestureRecognizer
@objc func moveObject(_ gesture: UIPanGestureRecognizer){
//1. Check That We Have A Valid Draggable View
guard let draggedObject = gesture.view else { return }
if gesture.state == .began || gesture.state == .changed {
//2. Set The Translation & Move The View
let translation = gesture.translation(in: self.view)
draggedObject.center = CGPoint(x: draggedObject.center.x + translation.x, y: draggedObject.center.y + translation.y)
gesture.setTranslation(CGPoint.zero, in: self.view)
}else if gesture.state == .ended {
}
}
这不是一个完整的例子,但希望它对你来说是一个很好的起点^ ______ ^。