【问题标题】:Swipe-able Table View Cell in iOS 9iOS 9 中可滑动的表格视图单元格
【发布时间】:2015-11-07 09:14:09
【问题描述】:

我希望我的表格列表具有类似 iOS 8 中的可滑动菜单(在 iOS 7 中首次引入)。

我已经找到a Ray Wenderlich guide that is clear 知道如何操作,但它是在一年零四个月前编写的,代码是用 Objective-C 编写的。

iOS 8 或即将推出的 iOS 9 是否最终将这个功能包含在 Apple 的 SDK 中?我知道他们几年前就内置了“滑动以显示删除功能”。如果 Apple 的新 iOS 将把它放在一个包装整齐的包装中交给我,我不想浪费我的时间来实现修补在一起的代码来模仿 iOS 8 的邮件功能。

【问题讨论】:

  • 有没有人在 Swift 中找到从左到右滑动的解决方案?从右到左似乎有很好的记录和讨论,但不是从左到右。

标签: swift uitableview custom-cell ios9 tableviewcell


【解决方案1】:

AFAIK 没有内置的即用型解决方案,即使在 iOS9 中,您也可能无法使用它,因为在可预见的未来您的应用程序不能只支持 iOS9。

相反,我建议您查看这个库:

https://github.com/CEWendel/SWTableViewCell

它非常易于配置,非常完善,并且在我从事的任何快速项目中都运行良好。

希望对你有帮助!

【讨论】:

  • 谢谢。刚开始开发,以前从未使用过 GitHub。我刚刚下载了 zip 文件并在 X-Code 中打开了该项目,然后运行该项目但得到“构建失败”。我是否必须将代码合并到我的项目中才能看到它是如何工作的?
  • 你最好安装 Cocoapods 作为依赖管理器;它是行业标准,将为您省去很多麻烦。更多关于 cocoapods 以及如何在这里使用它cocoapods.org
  • 感谢 Jiri,在简要阅读了 CocoaPods 之后,听起来我今晚必须进一步阅读才能理解它们。我急切地开始查看代码,而不是运行 github 项目。它在目标-C 中!我的应用程序使用 Swift,这是我熟悉的语言。我是否必须将 github 解决方案翻译成 Swift,或者,因为它们可以并排运行,我是否能够将 Objective-C ViewController 代码复制到我的 BasicCellViewController 中?
  • 使用 cocoapods,您可以并排运行库,如果您使用的是 iOS8+,则可以使用目标 C 和 swift。然后你可以在你的 swift 项目中无缝使用 Obj-C 代码(但它会隐藏在“pods”项目下),你唯一需要做的就是在你的“桥接头”中导入objective-c库developer.apple.com/library/prerelease/ios/documentation/Swift/…跨度>
  • 刚刚阅读了有关 CocoaPods (raywenderlich.com/97014/use-cocoapods-with-swift) 的信息,我认为这对我的大脑来说实在是太多了。我得到了这个概念,但在终端中实现它,使用工作区,让我的应用程序在未与我的其他代码合并的代码上运行......加上调整实际菜单功能以查看/执行我想要的方式......我的大脑会爆炸。将研究如何将那个 obj-c 粘贴进去并告诉我的应用程序我正在使用这两种语言。以前没做过,但看起来更简单
【解决方案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 {
}

【讨论】:

  • 我可以用十几行代码获得所有这些功能?或者您只是说将我最终使用的任何代码插入到该函数中,给定的代码甚至看起来都没有修改单元格。另外,尝试在 Swift 中解决这个问题。
  • 是的,您只需该代码即可获得所有功能。这是一个内置功能。哇,这甚至是正确的答案,有人投了反对票。我很惊讶。
  • 请注意,这从 iOS8+ 开始可用,并且它只允许您向左滑动,您必须进行自定义实现才能向右滑动。除此之外,还可以快速轻松地回答
  • 感谢您的分享。如果我太无能而无法实现完整菜单,那么我可能会使用这个更简单的解决方案。我投了赞成票,因为它是相关的,但我不能选择它作为答案,因为它没有回答如何模仿完整的 iOS8 邮件菜单的问题,而且它是用 Objective-C 编写的。
【解决方案3】:

试试这个,为 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]
}

也实现这个:(你可以让它有条件,但这里一切都是可编辑的)

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

【讨论】:

  • 这不能回答问题。我们正在尝试使用 swift 找到向左滑动的方法这不是这样做的
  • 谢谢!这显然没有处理左右滑动,但我还是决定放弃该功能。唯一不清楚的是如何在按下可能从表格中移动/删除单元格的按钮后自动刷新表格?
  • 不知道你的意思是tableview.reloadRowsAtIndexPaths ([indexpath] withRowAnimation: UITableViewRowAnimation.Automatic)和删除tableview.deleteRowsAtIndexPaths([indexpath], withRowAnimation: UITableViewRowAnimation.Automatic)
  • 是否可以通过点击单元格而不是滑动来打开编辑操作?
  • Swift 3 函数定义override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]?
【解决方案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】:

      此代码适用于我在 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的Delegate方法:-

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

      【讨论】:

      • 只用了 3 年 :) 感谢您的回答
      • 适用于iOS 11+
      【解决方案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])
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-06-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-03
        • 1970-01-01
        • 2015-03-07
        相关资源
        最近更新 更多