Подтвердить что ты не робот

Манипулятор для просмотра таблицы в iOS 9

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

Снимок экрана с кнопками сотовой ячейки таблицы

Я нашел руководство Ray Wenderlich, которое ясно о том, как это сделать, но было написано год и 4 месяца назад и код находится в Objective-C.

Неужели iOS 8 или предстоящая iOS 9 наконец включили эту функцию в Apple SDK? Я знаю, что они сделали "салфетки, чтобы показать функцию удаления", встроенную много лет назад. Я не хочу тратить свое время на реализацию кода с исправленными кодами, чтобы имитировать функцию почты iOS 8, если Apple iOS собирается передать ее мне в аккуратно упакованном пакете.

4b9b3361

Ответ 1

Попробуйте это. (Обновлено для Swift 3.0) (Документы разработчика)

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
    }

Ответ 2

Вы можете использовать метод делегата 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 {
}

Ответ 3

Этот код работает для меня в swift4.

enter image description here

Ответ на приведенном выше экране:

 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])
    }

enter image description here

Ответ экрана выше: -

 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])

    }

Напишите табличный метод делегата аналогично: -

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)

}

Ответ 4

Я нашел эту библиотеку 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

Ответ 5

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]
    }

}

Ответ 6

AFAIK не имеет встроенного готового решения, и даже если бы в iOS9, вы, вероятно, не сможете его использовать, поскольку вы можете не только поддерживать iOS9 в своем приложении в обозримом будущем.

Вместо этого я рекомендую вам изучить эту библиотеку:

https://github.com/CEWendel/SWTableViewCell

Он очень легко настраивается, полностью полируется и отлично работает в любом быстром проекте, над которым я работал.

Надеюсь, что это поможет!

Ответ 7

Это проще, чем вы думаете. Вот пример класса Swift с реализованным UITableView и способностью проводить UITableViewCell.

import UIKit

class ViewController: UIViewController {

    // MARK: Properties

    let strings = ["firstString", "secondString", "thirdString"]

    // MARK: Outlets

    @IBOutlet weak var tableView: UITableView!

    // MARK: Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
    }
}

extension ViewController: UITableViewDataSource, UITableViewDelegate {

    // MARK: UITableViewDataSource

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return objects.count
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier", for: indexPath)
        let currentString = strings[indexPath.row]
        cell.textLabel?.text = currentString
        return cell
    }

    // MARK: UITableViewDelegate

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }

    func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let leftAction = UIContextualAction(style: .normal, title:  "Red", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
            print("leftAction tapped")
            success(true)
        })

        leftAction.image = UIImage(named: "")
        leftAction.backgroundColor = UIColor.red

        return UISwipeActionsConfiguration(actions: [leftAction])
    }

    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let rightAction = UIContextualAction(style: .normal, title:  "Green", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
            print("rightAction tapped")
            success(true)
        })

        rightAction.image = UIImage(named: "")
        rightAction.backgroundColor = UIColor.green

        return UISwipeActionsConfiguration(actions: [rightAction])
    }

}