테이블뷰 여러 섹션의 리스트 롱프레스 드레그 변경

같은 섹션의 리스트에서만 변경 가능

import UIKit

class ViewController: UIViewController {
	let sections = ["Section1", "Section2", "Section3"]
    var menus = [
                ["VC1","VC2","VC3"],
                ["VC4","VC5","VC6"],
                ["VC7","VC8","VC9"],
    ]
    
    @IBOutlet weak var tableView: UITableView!
    
    var beginningItemSection: Int = -1
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    self.tableView.delegate = self
	self.tableView.dataSource = self
    
    //dragDelegate 설정
	self.tableView.dragInteractionEnabled = true
	self.tableView.dragDelegate = self
	self.tableView.dropDelegate = self
         
	self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
}

extension ViewController: UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return sections[section]
    }
}

extension ViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return menus[section].count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = UITableViewCell(style: .default, reuseIdentifier: .none)
        cell.textLabel?.text = menus[indexPath.section][indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let section = indexPath.section
        let row = indexPath.row

		let vc: ViewController = UIStoryboard(storyboard: .Main).instantiateViewController()
                
		guard let topVC = UIApplication.currentTopViewController() else {
			return
		}
		topVC.navigationController?.pushViewController(vc, animated: true)
    }
    
    // Move Row Instance Method
    func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        
        print("moveRowAt : \(sourceIndexPath.row) -> \(destinationIndexPath.row)")
        // 변경된 Cell의 순서에 맞게 menus List 순서 변경
        if sourceIndexPath.section == destinationIndexPath.section {
            // Cell 이름 리스트
            let moveCell = self.menus[sourceIndexPath.section][sourceIndexPath.row]
            self.menus[sourceIndexPath.section].remove(at: sourceIndexPath.row)
            self.menus[sourceIndexPath.section].insert(moveCell, at: destinationIndexPath.row)
        }
    }
}

/// LongPress Cell Move
// MARK:- UITableView UITableViewDragDelegate
extension ViewController: UITableViewDragDelegate {
    func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
        
        print("itemsForBeginning \(indexPath.section) / \(indexPath.row)")
        beginningItemSection = indexPath.section
        
        return [UIDragItem(itemProvider: NSItemProvider())]
    }
}
 
// MARK:- UITableViewDropDelegate
extension ViewController: UITableViewDropDelegate {
    func tableView(_ tableView: UITableView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UITableViewDropProposal {
        
        // 이동하는 Cell의 Section이 다른 Section으로 이동하면 cancel
        if beginningItemSection != destinationIndexPath?.section {
            return UITableViewDropProposal(operation: .cancel, intent: .unspecified)
        }
        
        print("withDestinationIndexPath \(destinationIndexPath?.section) / \(destinationIndexPath?.row)")
        
        if session.localDragSession != nil {
            return UITableViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
        }
        return UITableViewDropProposal(operation: .cancel, intent: .unspecified)
    }
    
    func tableView(_ tableView: UITableView, performDropWith coordinator: UITableViewDropCoordinator) {
    }
}

+ Recent posts