Table View 中开启自带文本菜单功能

长按所选的对象后,弹出文本菜单(Context Menu),允许用户进行剪切、复制、粘贴操作。默认情况下,文本菜单功能在 Table View 中是关闭状态。在本节教程中,将学习如何在 Table View Cell 中开启文本菜单功能,将所选的文本复制到 Text Filed(文本输入框)中。

1.您可以创建一个swift工程.

2.在viewController中创建一个tableview和一个textfield.

3.初始化几条假数据,实现tabelview的代理方法.

4.实现代理

varpasteBoard =UIPasteboard.generalPasteboard()

vartableData: [String] = ["swift","o'c","java","html"]

funcnumberOfSections(intableView: UITableView)->Int{

return1

}

functableView(_tableView: UITableView, numberOfRowsInSection section: Int)->Int{

returntableData.count

}

functableView(_tableView: UITableView, cellForRowAt indexPath: IndexPath)->UITableViewCell{

letcell = tableView.dequeueReusableCell(withIdentifier:"cell",for: indexPath)

cell.textLabel?.text = tableData[indexPath.row]

returncell

}

5.想要开启文本菜单功能,需要实现以下三个 delegate 方法。

functableView(_tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath)->Bool

{

returntrue

}

functableView(_tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?)->Bool{

if(action == #selector(UIResponderStandardEditActions.copy(_:))) {

returntrue

}

returnfalse

}

functableView(_tableView: UITableView, performAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?){

letcell = tableView.cellForRow(at: indexPath)

pasteBoard.string = cell!.textLabel?.text

}

//tableView:shouldShowMenuForRowAt方法必须返回 true,才能长按显示文本菜单。

//tableView:canPerformAction:forRowAt方法,让文本菜单只显示 copy(复制)一个选项。

//tableView:performAction:forRowAt:withSender方法将选中的文本复制到 pasteBoard 变量中。

你可能感兴趣的:(Table View 中开启自带文本菜单功能)