Swipe-able Table View Cell in iOS 9
Solution 1
Try this, updated for Swift 3 (Developer Docs)
override func tableView(_ tableView: UITableView, editActionsForRowAt: IndexPath) -> [UITableViewRowAction]? {
let more = UITableViewRowAction(style: .normal, title: "More") { action, index in
print("more button tapped")
}
more.backgroundColor = .lightGray
let favorite = UITableViewRowAction(style: .normal, title: "Favorite") { action, index in
print("favorite button tapped")
}
favorite.backgroundColor = .orange
let share = UITableViewRowAction(style: .normal, title: "Share") { action, index in
print("share button tapped")
}
share.backgroundColor = .blue
return [share, favorite, more]
}
Also implement this: (You can make it conditional, but here everything is editable)
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
Solution 2
This code is work for me in the swift4.
Answer of the above screen is:-
func tableView(_ tableView: UITableView,
trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
{
// Write action code for the trash
let TrashAction = UIContextualAction(style: .normal, title: "Trash", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
print("Update action ...")
success(true)
})
TrashAction.backgroundColor = .red
// Write action code for the Flag
let FlagAction = UIContextualAction(style: .normal, title: "Flag", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
print("Update action ...")
success(true)
})
FlagAction.backgroundColor = .orange
// Write action code for the More
let MoreAction = UIContextualAction(style: .normal, title: "More", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
print("Update action ...")
success(true)
})
MoreAction.backgroundColor = .gray
return UISwipeActionsConfiguration(actions: [TrashAction,FlagAction,MoreAction])
}
Answer of the above screen:-
func tableView(_ tableView: UITableView,
leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
{
let closeAction = UIContextualAction(style: .normal, title: "Mark as Read", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
print("CloseAction ...")
success(true)
})
closeAction.backgroundColor = .blue
return UISwipeActionsConfiguration(actions: [closeAction])
}
Write tableview Delegate method likewise:-
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrPerson.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let personName = arrPerson[indexPath.row]
cell.textLabel?.text = personName.personName
return cell
}
And in the viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
tblView.delegate = self
tblView.dataSource = self
let person1 = personData(personName: "Jonny", personAge: 30)
let person2 = personData(personName: "Chandan", personAge: 20)
let person3 = personData(personName: "Gopal", personAge: 28)
arrPerson.append(person1)
arrPerson.append(person2)
arrPerson.append(person3)
}
Solution 3
You can use a UITableView delegate method to ask for those actions. Implement this method as follows:
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewRowAction *modifyAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"Modify" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
// Respond to the action.
}];
modifyAction.backgroundColor = [UIColor blueColor];
return @[modifyAction];
}
You can of course return multiple actions and customize the text and background color.
Implementing this method is also required to make the row editable:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
}
Solution 4
I found this library MGSwipeTableCell After searching a lot to implement a slide cell in table view using swift I found this one and its just one line of code to do the implementation and found it extremely useful.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let reuseIdentifier = "programmaticCell"
var cell = self.table.dequeueReusableCellWithIdentifier(reuseIdentifier) as! MGSwipeTableCell!
if cell == nil
{
cell = MGSwipeTableCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: reuseIdentifier)
}
cell.textLabel!.text = "Title"
cell.detailTextLabel!.text = "Detail text"
cell.delegate = self //optional
//configure left buttons
cell.leftButtons = [MGSwipeButton(title: "", icon: UIImage(named:"check.png"), backgroundColor: UIColor.greenColor())
,MGSwipeButton(title: "", icon: UIImage(named:"fav.png"), backgroundColor: UIColor.blueColor())]
cell.leftSwipeSettings.transition = MGSwipeTransition.Rotate3D
//configure right buttons
cell.rightButtons = [MGSwipeButton(title: "Delete", backgroundColor: UIColor.redColor())
,MGSwipeButton(title: "More",backgroundColor: UIColor.lightGrayColor())]
cell.rightSwipeSettings.transition = MGSwipeTransition.Rotate3D
return cell
}
Thats the only function you'll have to implement and update your pod file
Solution 5
Swift 3 complete solution:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableView.tableFooterView = UIView(frame: CGRect.zero) //Hiding blank cells.
tableView.separatorInset = UIEdgeInsets.zero
tableView.dataSource = self
tableView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath)
return cell
}
//Enable cell editing methods.
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let more = UITableViewRowAction(style: .normal, title: "More") { action, index in
//self.isEditing = false
print("more button tapped")
}
more.backgroundColor = UIColor.lightGray
let favorite = UITableViewRowAction(style: .normal, title: "Favorite") { action, index in
//self.isEditing = false
print("favorite button tapped")
}
favorite.backgroundColor = UIColor.orange
let share = UITableViewRowAction(style: .normal, title: "Share") { action, index in
//self.isEditing = false
print("share button tapped")
}
share.backgroundColor = UIColor.blue
return [share, favorite, more]
}
}
![Dave G](https://i.stack.imgur.com/1AaPo.jpg?s=256&g=1)
Dave G
Hi I was an analyst. I used to standardize data, then analyze, summarize, and share it. I built reports in Excel, most of which were automated. I was big into report design, keeping them clean and visual. But then I quit my job. Now I'm traveling and trying to learn iOS development.
Updated on September 28, 2021Comments
-
Dave G over 2 years
I want my table list to have a swipe-able menu like in iOS 8 (first introduced in iOS 7).
I've found a Ray Wenderlich guide that is clear on how to do it, but it was written a year and 4 months ago and the code is in Objective-C.
Did iOS 8 or the upcoming iOS 9 finally include this function in Apple's SDK? I know they made the "swipe to reveal delete function" built-in years ago. I don't want to waste my time implementing patched-together code to mimic the iOS 8 mail function, if Apple's new iOS is going to hand it to me in a neatly wrapped package.
-
Dave G almost 9 yearsThanks. New to developing and never used GitHub before. I just downloaded the zip file and opened the project in X-Code, and then ran the project but got "Build Failed". Do I have to merge the code into my project before I can see how it works?
-
Jiri Trecak almost 9 yearsYou are better of installing Cocoapods as dependency manager ; It is industry standard and will save you A LOT of headache. More aboout cocoapods and how to use it here cocoapods.org
-
Dave G almost 9 yearsI can obtain all that functionality with just a dozen lines of code? Or you're just saying to insert whatever code I do end up using into that function None of the given code even looks like it modifies the cell. Also, trying to resolve this in Swift.
-
BalestraPatrick almost 9 yearsYes, you can obtain all the functionalities with only that code. It's a built-in feature. Wow, this is even the correct answered and someone down voted it. I'm surprised.
-
Jiri Trecak almost 9 yearsBe aware that this is available since iOS8+ and it ONLY allows you to swipe left, you have to make custom implementation in order to do swipe right. Other than that, quick and easy answer as well
-
Dave G almost 9 yearsThanks Jiri, after briefly reading about CocoaPods it sounds like I'll have to do further reading tonight to understand them. I got eager and instead of running the github project I just started looking at the code. It's in objective-C! My app is in Swift and that's the language I am familiar with. Would I have to translate the github solution into Swift or, since they can be run side by side, would I be able to copy the Objective-C ViewController code into my BasicCellViewController?
-
Jiri Trecak almost 9 yearsWith cocoapods, you run libraries side by side, objective C and swift if you are using iOS8+. Then you can seamlessly use Obj-C code in your swift project (but it will be hidden under "pods" project), the only thing you have to do is import objective-c library in your "Bridging Header" developer.apple.com/library/prerelease/ios/documentation/Swift/…
-
Dave G almost 9 yearsThank you for sharing it. If I am too incompetent to implement the full menu then I might use this simpler solution. I gave it an up-vote since it is relevant but I can't pick it as an answer as it doesn't answer the question of how to mimic the full iOS8 Mail menu, plus it's written in objective-C.
-
Dave G almost 9 yearsJust read about CocoaPods (raywenderlich.com/97014/use-cocoapods-with-swift), I think that'll be too much for my brain to chew on. I get the concept but implementing it in terminal, uses workspaces, having my app run on code not merged in with my other code... plus tweaking the actual menu function to look/act how I want it too... my brain would explode. Going to look into how I'd just paste that obj-c in and tell my app I'm using both languages. Haven't done that before but seems simpler
-
Dave G almost 9 yearsLet us continue this discussion in chat.
-
Somu over 8 yearsThis doesn't answer the question. We are trying to figure a way out to the left swipe using swift This does not do that
-
Dave G over 8 yearsThanks! This obviously didn't handle the left-right swipe, but I've decided to abandon that function anyhow. The only thing that isn't clear is how to get the table to automatically refresh after pushing a button that might move/delete the cell from the table?
-
jose920405 over 8 yearsDo not know if you mean
tableview.reloadRowsAtIndexPaths ([indexpath] withRowAnimation: UITableViewRowAnimation.Automatic)
and for deletetableview.deleteRowsAtIndexPaths([indexpath], withRowAnimation: UITableViewRowAnimation.Automatic)
-
Heysem Katibi over 8 yearsIs it possible to open Edit Action by tapping the cell instead of swiping it?
-
jose920405 over 8 years@MoHaKa With this logic I think not. I see only two options: 1) With the tap you can simulate the swipe for this to work (not recommended). 2) Display a customized pop up with the options you need when you click on the cell.
-
Muruganandham K almost 8 years@jose920405 how to add image here.. i have tried to set image as backgroundcolor. no luck
-
jose920405 almost 8 years@MuruganandhamK You have already tried this? ==> stackoverflow.com/questions/29335104/…
-
user1007522 over 7 yearsThank you so much. On iOS 9 it's not import to implement the commitEditingStyle but on iOS 8 it doesn't work without it. You saved me a lot of time.
-
Happiehappie over 7 yearsJust wondering, is it possible to create a custom view? Cause what if I would like to have two different background colors for my custom action?
-
jose920405 over 7 yearsSomething like stackoverflow.com/questions/29421894/… ?
-
David Corbin over 7 yearsSwift 3 function definition
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]?
-
Ron Srebro almost 6 yearsTook only 3 years :) Thanks for answering
-
cdub almost 6 yearsIt is for iOS 11+
-
Mayur Shinde almost 5 yearsI have image but size is bigger than cell size. Then how to auto adjust image in cell action ?