Wie erhalte ich die Schaltfläche zum Löschen, wenn ich auf einem UITableViewCell
wische? Das Ereignis wird niemals ausgelöst und die Schaltfläche "Löschen" wird niemals angezeigt.
Während des Starts in (-viewDidLoad or in storyboard)
mache:
self.tableView.allowsMultipleSelectionDuringEditing = NO;
Überschreiben, um das bedingte Bearbeiten der Tabellenansicht zu unterstützen. Dies muss nur implementiert werden, wenn Sie NO
für einige Artikel zurückgeben. Standardmäßig können alle Elemente bearbeitet werden.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return YES if you want the specified item to be editable.
return YES;
}
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
//add code here for when you hit delete
}
}
Diese Antwort wurde aktualisiert auf Swift 3
Ich finde es immer schön, ein sehr einfaches, in sich geschlossenes Beispiel zu haben, damit beim Erlernen einer neuen Aufgabe nichts vorausgesetzt wird. Diese Antwort dient zum Löschen von UITableView
Zeilen. Das Projekt läuft folgendermaßen ab:
Dieses Projekt basiert auf ITableView-Beispiel für Swift .
Erstellen Sie ein neues Projekt und ersetzen Sie den ViewController.Swift-Code durch den folgenden.
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// These strings will be the data for the table view cells
var animals: [String] = ["Horse", "Cow", "Camel", "Pig", "Sheep", "Goat"]
let cellReuseIdentifier = "cell"
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// It is possible to do the following three things in the Interface Builder
// rather than in code if you prefer.
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
tableView.delegate = self
tableView.dataSource = self
}
// number of rows in table view
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.animals.count
}
// create a cell for each table view row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
cell.textLabel?.text = self.animals[indexPath.row]
return cell
}
// method to run when table view cell is tapped
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You tapped cell number \(indexPath.row).")
}
// this method handles row deletion
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// remove the item from the data model
animals.remove(at: indexPath.row)
// delete the table view row
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Not used in our example, but if you were adding a new row, this is where you would do it.
}
}
}
Die Einzelschlüsselmethode im obigen Code, die das Löschen von Zeilen ermöglicht, ist die letzte. Hier ist es wieder zur Hervorhebung:
// this method handles row deletion
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// remove the item from the data model
animals.remove(at: indexPath.row)
// delete the table view row
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Not used in our example, but if you were adding a new row, this is where you would do it.
}
}
Fügen Sie dem View Controller im Storyboard ein UITableView
hinzu. Verwenden Sie das automatische Layout, um die vier Seiten der Tabellenansicht an den Rändern des View Controllers zu befestigen. Steuern Sie das Ziehen aus der Tabellenansicht im Storyboard in die Zeile @IBOutlet var tableView: UITableView!
im Code.
Das ist alles. Sie sollten jetzt in der Lage sein, Ihre App auszuführen und Zeilen zu löschen, indem Sie nach links wischen und auf "Löschen" tippen.
Ändern Sie den Text der Schaltfläche "Löschen"
Fügen Sie die folgende Methode hinzu:
func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
return "Erase"
}
Benutzerdefinierte Schaltflächenaktionen
Fügen Sie die folgende Methode hinzu.
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
// action one
let editAction = UITableViewRowAction(style: .default, title: "Edit", handler: { (action, indexPath) in
print("Edit tapped")
})
editAction.backgroundColor = UIColor.blue
// action two
let deleteAction = UITableViewRowAction(style: .default, title: "Delete", handler: { (action, indexPath) in
print("Delete tapped")
})
deleteAction.backgroundColor = UIColor.red
return [editAction, deleteAction]
}
Beachten Sie, dass dies nur unter iOS 8 verfügbar ist. Weitere Informationen finden Sie unter diese Antwort .
Aktualisiert für iOS 11
Aktionen können mit Methoden, die der UITableViewDelegate-API in iOS 11 hinzugefügt wurden, entweder vor oder nach der Zelle platziert werden.
func tableView(_ tableView: UITableView,
leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
{
let editAction = UIContextualAction(style: .normal, title: "Edit", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
success(true)
})
editAction.backgroundColor = .blue
return UISwipeActionsConfiguration(actions: [editAction])
}
func tableView(_ tableView: UITableView,
trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
{
let deleteAction = UIContextualAction(style: .normal, title: "Delete", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
success(true)
})
deleteAction.backgroundColor = .red
return UISwipeActionsConfiguration(actions: [deleteAction])
}
Dieser Code zeigt, wie das Löschen implementiert wird.
#pragma mark - UITableViewDataSource
// Swipe to delete.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
[_chats removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
}
Fügen Sie optional in Ihrer Initialisierungsüberschreibung die folgende Zeile hinzu, um das Schaltflächenelement Bearbeiten anzuzeigen:
self.navigationItem.leftBarButtonItem = self.editButtonItem;
Hinweis: Ich habe nicht genug Ruf, um einen Kommentar in der Antwort von Kurbz zu posten.
Die Antwort von Kurbz ist richtig. Aber bei mir hat es nie geklappt.
Nach einigen Nachforschungen wurde mir klar, dass Wischen zum Löschen geschieht, wenn die Tabellenansicht NICHT bearbeitet wird..
Ich habe das nie explizit als solches gesehen. Sofern ich mich nicht irre, habe ich keinen anderen Weg gefunden, um es funktionieren zu lassen.
Beim Bearbeiten wird das Steuerelement zum Löschen und/oder Neuanordnen angezeigt.
Ich hatte ein Problem, das ich gerade gelöst habe, und teile es, da es möglicherweise jemandem hilft.
Ich habe eine UITableView und habe die gezeigten Methoden hinzugefügt, um das Löschen durch Wischen zu ermöglichen:
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return YES if you want the specified item to be editable.
return YES;
}
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
//add code here for when you hit delete
}
}
Ich arbeite an einem Update, mit dem ich die Tabelle in den Bearbeitungsmodus versetzen und die Mehrfachauswahl aktivieren kann. Dazu habe ich den Code aus Apples Beispiel TableMultiSelect hinzugefügt. Sobald ich das zum Laufen brachte, stellte ich fest, dass mein Wischen die Löschfunktion nicht mehr funktionierte.
Es stellte sich heraus, dass das Hinzufügen der folgenden Zeile zu viewDidLoad das Problem war:
self.tableView.allowsMultipleSelectionDuringEditing = YES;
Wenn diese Zeile aktiviert ist, funktioniert die Mehrfachauswahl, die zu löschende Streifbewegung jedoch nicht. Ohne die Linie war es umgekehrt.
Das Update:
Fügen Sie Ihrem viewController die folgende Methode hinzu:
- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
self.tableView.allowsMultipleSelectionDuringEditing = editing;
[super setEditing:editing animated:animated];
}
Dann sollten Sie in Ihrer Methode, die die Tabelle in den Bearbeitungsmodus versetzt (z. B. durch Drücken einer Taste), Folgendes verwenden:
[self setEditing:YES animated:YES];
anstatt von:
[self.tableView setEditing:YES animated:YES];
Dies bedeutet, dass die Mehrfachauswahl nur aktiviert ist, wenn sich die Tabelle im Bearbeitungsmodus befindet.
nterhalb von UITableViewDataSource finden Sie Informationen zum Löschen durch Wischen.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return YES if you want the specified item to be editable.
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
[arrYears removeObjectAtIndex:indexPath.row];
[tableView reloadData];
}
}
arrYears ist ein NSMutableArray und lädt dann die tableView neu
Swift
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyleDelete {
arrYears.removeObjectAtIndex(indexPath.row)
tableView.reloadData()
}
}
In iOS 8 und Swift 2.0 versuchen Sie bitte Folgendes:
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// let the controller to know that able to edit tableView's row
return true
}
override func tableView(tableView: UITableView, commitEdittingStyle editingStyle UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
// if you want to apply with iOS 8 or earlier version you must add this function too. (just left in blank code)
}
override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
// add the action button you want to show when swiping on tableView's cell , in this case add the delete button.
let deleteAction = UITableViewRowAction(style: .Default, title: "Delete", handler: { (action , indexPath) -> Void in
// Your delete code here.....
.........
.........
})
// You can set its properties like normal button
deleteAction.backgroundColor = UIColor.redColor()
return [deleteAction]
}
@Kurbz's Antwort ist fantastisch, aber ich möchte diese Notiz hinterlassen und hoffe, dass diese Antwort den Leuten etwas Zeit ersparen kann.
Ich hatte gelegentlich diese Zeilen in meinem Controller, und die Wischfunktion funktionierte nicht.
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
return UITableViewCellEditingStyleNone;
}
Wenn Sie UITableViewCellEditingStyleInsert
oder UITableViewCellEditingStyleNone
als Bearbeitungsstil verwenden, funktioniert die Wischfunktion nicht. Sie können nur UITableViewCellEditingStyleDelete
verwenden. Dies ist der Standardstil.
Sie müssen nur diese beiden Funktionen aktivieren:
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCellEditingStyle.delete {
tableView.reloadData()
}
}
Swift 4
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let delete = UITableViewRowAction(style: .destructive, title: "delete") { (action, indexPath) in
// delete item at indexPath
tableView.deleteRows(at: [indexPath], with: .fade)
}
return [delete]
}
Dies kann auch in Swift mit der folgenden Methode erreicht werden
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if (editingStyle == UITableViewCellEditingStyle.Delete){
testArray.removeAtIndex(indexPath.row)
goalsTableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}
Ich weiß, ist alte Frage, aber @Kurbz Antwort brauchen nur diese für Xcode 6.3.2 und SDK 8.3
Ich muss [tableView beginUpdates]
und [tableView endUpdates]
hinzufügen (danke an @ bay.phillips hier )
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle: (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
// Open "Transaction"
[tableView beginUpdates];
if (editingStyle == UITableViewCellEditingStyleDelete) {
// your code goes here
//add code here for when you hit delete
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
// Close "Transaction"
[tableView endUpdates];
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
//add code here for when you hit delete
[dataSourceArray removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
}
Wenn Sie eine Zelle Ihrer Tabellenansicht entfernen, müssen Sie auch Ihr Array-Objekt am Index x entfernen.
Ich denke, Sie können es mit einer Wischgeste entfernen. Die Tabellenansicht ruft den Delegierten auf:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
//add code here for when you hit delete
[dataSourceArray removeObjectAtIndex:indexPath.row];
}
}
Nach dem Entfernen des Objekts. Sie müssen die Tabellenansicht neu laden. Fügen Sie die folgende Zeile in Ihren Code ein:
[tableView reloadData];
danach haben Sie die Zeile erfolgreich gelöscht. Und wenn Sie die Ansicht neu laden oder der DataSource Daten hinzufügen, ist das Objekt nicht mehr vorhanden.
Für alle anderen ist die Antwort von Kurbz richtig.
Ich wollte Sie nur daran erinnern, dass die Delegierungsfunktion nicht ausreicht, wenn Sie das Objekt aus dem DataSource-Array entfernen möchten.
Ich hoffe, ich habe dir geholfen.
Schreiben Sie für Swift einfach diesen Code
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
print("Delete Hit")
}
}
Schreiben Sie für Ziel C einfach diesen Code
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
NSLog(@"index: %@",indexPath.row);
}
}
Swift 2.2:
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView,
editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
let delete = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "DELETE"){(UITableViewRowAction,NSIndexPath) -> Void in
print("Your action when user pressed delete")
}
let edit = UITableViewRowAction(style: UITableViewRowActionStyle.Normal, title: "EDIT"){(UITableViewRowAction,NSIndexPath) -> Void in
print("Your action when user pressed edit")
}
return [delete, block]
}
aktivieren Sie für Swift4-Code zuerst die Bearbeitung:
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
anschließend fügen Sie dem Bearbeitungsdelegaten eine Löschaktion hinzu:
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let action = UITableViewRowAction(style: .destructive, title: "Delete") { (_, index) in
// delete model object at the index
self.models[index.row]
// then delete the cell
tableView.beginUpdates()
tableView.deleteRows(at: [index], with: .automatic)
tableView.endUpdates()
}
return [action]
}