🖥️
iOS App with Pop
Swift 4
Swift 4
  • iOS App development
  • Create New Project
  • Introduction to Xcode
  • App's life cycle
  • UIViewController
  • Storyboard
  • First Run
  • Display todo list
  • Basic Auto Layout
  • MVC
  • Model
  • Binding TableView
  • Binding TableViewCell
  • TableViewDelegate
  • Add navigationBar with + button
  • Add new item page
  • TextField and Switch
  • Binding action
  • Add mock item to todo list
  • Finish add item
  • Delete todo item
  • Edit todo item
  • Custom new layout
  • Adding new delegate
  • Refactor
  • Save data
  • Pushing edit view
  • Large navigation
  • Drag item
  • Drop item (in app)
  • Where to go from here?
Powered by GitBook
On this page

Drop item (in app)

แล้วก็ทำให้วางได้

คล้าย ๆ กับการทำให้ลากได้ ให้เราบอก TableView ว่า dropDelegate คือฉันนะ (TodoListViewController)

override func viewDidLoad() {
    super.viewDidLoad()
    loadTodo()
    tableView?.dragDelegate = self
    tableView?.dragInteractionEnabled = true
    
    tableView?.dropDelegate = self
}

ประกาศ conform protocol

UITableViewDropDelegate

เพิ่มฟังก์ชั่น UITableViewDropDelegate

func tableView(_ tableView: UITableView, performDropWith coordinator: UITableViewDropCoordinator) {}

func tableView(_ tableView: UITableView, canHandle session: UIDropSession) -> Bool {
    return session.localDragSession != nil
}

func tableView(_ tableView: UITableView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UITableViewDropProposal {
    return UITableViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
}

บรรทัดที่ 4 เป็นการบอกว่า drop จากเฉพาะ localDrag นะที่ทำได้ บรรทัดที่ 8 เป็นการระบุว่าเป็นการ move เพื่อให้หน้าจอแสดงไอคอน move

เนื่องจากเป็นการ reordering ทาง Apple บอกว่าจะไม่เรียกฟังก์ชั่น performDrop นะ ให้ใช้ TableViewDataSource อันเก่า

เราก็มาเพิ่ม UITableViewDataSource 2 ฟังก์ชั่นนี้

func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
    return true
}

func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
    todo.move(from: sourceIndexPath.row, to: destinationIndexPath.row)
    saveTodo()
}

เมื่อเรารันอีกทีคราวนี้เราก็จะลากวางได้ละ เป็นอันเสร็จ

สามารถอ่านหัวข้อ Drag and Drop เพิ่มเติมได้ที่

PreviousDrag itemNextWhere to go from here?

Last updated 6 years ago

Supporting Drag and Drop in Table Views
Adopting Drag and Drop in a Table View