UicollectionView Drag-n-Drop в SwiftIOS

Программируем под IOS
Ответить
Anonymous
 UicollectionView Drag-n-Drop в Swift

Сообщение Anonymous »

Я делаю проект с uicollectionView в Swift, мне нужно выполнить перетаскивание с каждыми коробками и поменять их положение. Каждое ящики имеют разные данные и разные размеры, поэтому пользователям необходимо манипулировать своим макетом, потому что мне нужно, чтобы пользователи могли перетаскивать эти представления. Я написал код, но когда я начну Drag-n-Drop, событие передаст их данные вместо самого ящиков. Как я могу решить это? < /p>

import UIKit

class ViewController: UIViewController {

var cellIds = ["1","2","3"]

@IBOutlet weak var collectionView: UICollectionView!
fileprivate var longPressGesture = UILongPressGestureRecognizer();

let cellSizes = [
CGSize(width:190, height:200),
CGSize(width:190, height:200),
CGSize(width:190, height:200),

]

@objc func longTap(_ gesture: UIGestureRecognizer){

switch(gesture.state) {
case .began:
guard let selectedIndexPath = collectionView.indexPathForItem(at: gesture.location(in: collectionView)) else {
return
}
collectionView.beginInteractiveMovementForItem(at: selectedIndexPath)
case .changed:
collectionView.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view!))
case .ended:
collectionView.endInteractiveMovement()
//doneBtn.isHidden = false
//longPressedEnabled = true
self.collectionView.reloadData()
default:
collectionView.cancelInteractiveMovement()
}
}

override func viewDidLoad() {
super.viewDidLoad()

longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.longTap(_:)))
collectionView.addGestureRecognizer(longPressGesture)

collectionView!.register(UICustomCollectionViewCell.self, forCellWithReuseIdentifier: "MenuCell")

self.automaticallyAdjustsScrollViewInsets = false
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
//top, left, bottom, right
return UIEdgeInsets(top: 130, left: 1, bottom: 0, right: 10)
}

}

extension ViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// print("User tapped on \(cellIds[indexPath.row])")
}

func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
return true
}

func userDidEndDragging(_ cell: UICollectionViewCell?) {

}

func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let item = cellIds.remove(at: sourceIndexPath.item)
cellIds.insert(item, at: destinationIndexPath.item)
print(cellIds);
}
}

extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return cellIds.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MenuCell", for: indexPath) as? UICustomCollectionViewCell

cell!.layer.cornerRadius=10
cell!.layer.masksToBounds=true

var id = cellIds[indexPath.row];

if (id == "1")
{

cell?.lblTest1.text = "amsterdam";
cell?.lblTest1.tag = 100
}
if (id == "2")
{
cell?.lblTest2.text = "madrid";
cell?.lblTest2.tag = 101

}

if (id == "3")
{
cell?.lblTest3.text = "istanbul";
cell?.lblTest3.tag = 102
}

return cell ?? UICollectionViewCell()

}
}

extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return cellSizes[indexPath.item]
}
}

import UIKit
class UICustomCollectionViewCell: UICollectionViewCell {

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

override func prepareForReuse() {
super.prepareForReuse()
}

override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(lblTest1)
self.addSubview(lblTest2)
self.addSubview(lblTest3)
}

var lblTest1:UILabel = {
let label1 = UILabel(frame: CGRect(x:10, y: 20, width: 90 , height: 40))
label1.lineBreakMode = .byWordWrapping
label1.numberOfLines = 0
label1.tag = 100;
label1.tintColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
return label1
}()

var lblTest2:UILabel = {
let label2 = UILabel(frame: CGRect(x:10, y: 20, width: 90 , height: 40))
label2.lineBreakMode = .byWordWrapping
label2.numberOfLines = 0
label2.tag = 101;
label2.tintColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
return label2
}()

var lblTest3:UILabel = {
let label3 = UILabel(frame: CGRect(x:10, y: 20, width: 90 , height: 40))
label3.lineBreakMode = .byWordWrapping
label3.numberOfLines = 0
label3.tag = 102;
label3.tintColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
return label3
}()

override func layoutSubviews() {
super.layoutSubviews()
}
}


Подробнее здесь: https://stackoverflow.com/questions/583 ... p-at-swift
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «IOS»