🖥️
iOS App with Pop
UIKit Swift 5
UIKit Swift 5
  • iOS App development
  • Swift
    • Variable & Constant
    • Number & String
    • Operator
    • Array, Dictionary & Tuple
    • Enum
    • Optional
    • Function
    • Class & Struct
    • Branching
    • Loops
    • Error handler
    • Protocol
    • Extension
  • Create New Project
  • Introduction to Xcode
  • Scene-Based 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
  • What is weak?
  • Finish add item
  • Delete todo item
  • Edit todo item
  • Custom new layout
  • Adding new delegate
  • Refactor
  • Pushing edit view
  • Large navigation
  • Drag item
  • Drop item (in app)
  • Save data
  • Where to go from here?
Powered by GitBook
On this page

Drop item (in app)

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

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

override func viewDidLoad() {
    super.viewDidLoad()
    todo.add(item: TodoItem(title: "Download XCode", isDone: true))
    todo.add(item: TodoItem(title: "Buy milk"))
    todo.add(item: TodoItem(title: "Learning Swift", isDone: false))
    
    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 {
    session.localDragSession != nil
}

func tableView(_ tableView: UITableView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UITableViewDropProposal {
    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 {
    true
}

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

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

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

PreviousDrag itemNextSave data

Last updated 2 years ago

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