Swipe-возможность просмотра таблицы ячейки в iOS 9
Я хочу, чтобы в моем списке таблиц было меню с возможностью прокрутки, как в iOS 8 (впервые введено в iOS 7).

Я нашел руководство Рэй Вендерлих, что понятно о том, как это сделать, но это было написано год и 4 месяца назад, и код находится в Objective-C.
была ли iOS 8 или предстоящая iOS 9, наконец, включить эту функцию в SDK от Apple? Я знаю, что они сделали встроенный" swipe to reveal delete function " несколько лет назад. Я не хочу тратить свою время реализации исправленного кода для имитации почтовой функции iOS 8, если новая iOS от Apple собирается передать ее мне в аккуратно упакованном пакете.
6 ответов:
попробуйте это. (Обновлен для Swift 3.0) ( 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] }также реализуйте это: (вы можете сделать его условным, но здесь все редактируется)
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true }(Старая Версия)
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { let more = UITableViewRowAction(style: .Normal, title: "More") { action, index in print("more button tapped") } more.backgroundColor = UIColor.lightGrayColor() let favorite = UITableViewRowAction(style: .Normal, title: "Favorite") { action, index in print("favorite button tapped") } favorite.backgroundColor = UIColor.orangeColor() let share = UITableViewRowAction(style: .Normal, title: "Share") { action, index in print("share button tapped") } share.backgroundColor = UIColor.blueColor() return [share, favorite, more] } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // the cells you would like the actions to appear needs to be editable return true }
вы можете использовать метод делегата UITableView, чтобы запросить эти действия. Реализуйте этот метод следующим образом:
- (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]; }конечно, вы можете вернуть несколько действий и настроить цвет текста и фона.
реализация этого метода также требуется, чтобы сделать строку редактируемой:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { }
Я нашел эту библиотеку MGSwipeTableCell После большого поиска для реализации ячейки слайда в табличном представлении с помощью swift я нашел этот и его только одну строку кода для реализации и нашел его чрезвычайно полезным.
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 }Это единственная функция, которую вам нужно будет реализовать и обновить файл pod
Swift 3 полное решение:
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] } }
этот код работает для меня в swift4.
ответ на экране выше: -
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]) }ответ выше:-
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]) }написать метод делегата tableview аналогично: -
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 }и в 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) }
AFAIK нет встроенного готового решения, и даже если бы оно было в iOS9, вы, вероятно, не сможете его использовать, поскольку вы не можете поддерживать iOS9 только в своем приложении в обозримом будущем.
вместо этого я рекомендую вам заглянуть в эту библиотеку:
https://github.com/CEWendel/SWTableViewCell
Он очень легко настраивается, довольно полируется и хорошо работает в любом проекте swift, над которым я работал.
надеюсь, что это помогает!


Comments