问题描述
我在UITableViewCell
的最底部有一个tableview
,它的功能是将新对象添加到列表中。但我也希望用户能够移动他的对象。这就是我无法解决的问题:UITableViewCell
为真时,如何使此tableView.isEditing
不可移动,因此即使在用户尝试将其移动到该位置时,它也始终位于该部分的底部? / p>
解决方法
这是一个防止行被移到最后一行之外的简单示例:
class ReorderViewController: UITableViewController {
var myData = ["One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Don't let me move!"]
override func viewDidLoad() {
super.viewDidLoad()
let btn = UIBarButtonItem(barButtonSystemItem: .edit,target: self,action: #selector(self.startEditing(_:)))
navigationItem.rightBarButtonItem = btn
tableView.register(UITableViewCell.self,forCellReuseIdentifier: "cell")
}
@objc func startEditing(_ sender: Any) {
isEditing = !isEditing
}
override func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
return myData.count
}
override func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell",for: indexPath)
cell.textLabel?.text = myData[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView,canMoveRowAt indexPath: IndexPath) -> Bool {
// don't allow last row to move
return indexPath.row < (myData.count - 1)
}
override func tableView(_ tableView: UITableView,targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath,toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
// if user tries to drop past last row
if proposedDestinationIndexPath.row == myData.count - 1 {
// send it back to original row
return sourceIndexPath
}
return proposedDestinationIndexPath
}
override func tableView(_ tableView: UITableView,moveRowAt sourceIndexPath: IndexPath,to destinationIndexPath: IndexPath) {
let itemToMove = myData[sourceIndexPath.row]
myData.remove(at: sourceIndexPath.row)
myData.insert(itemToMove,at: destinationIndexPath.row)
}
}