繁体   English   中英

如何在 Swift 中的 UITableViewCell 上添加带有单击事件的按钮?

[英]How to add a button with click event on UITableViewCell in Swift?

在我的主页中,我为 UITableViewCell 创建了一个 xib 文件。 我正在从那个 xib 文件加载单元格并且它工作正常。

在单元格内部,我有一些标签和按钮。 我的目标是通过单击单元格上的按钮来更改标签。

我的代码喜欢下面

import UIKit


class SepetCell: UITableViewCell{

    @IBOutlet var barcode: UILabel!
    @IBOutlet var name: UILabel!
    @IBOutlet var fav: UIButton!
    @IBOutlet var strep: UIStepper!
    @IBOutlet var times: UILabel!



    @IBAction func favoriteClicked(sender: UIButton) {
        println(sender.tag)
        println(times.text)

        SepetViewController().favorite(sender.tag)



    }
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}

这是我的 .swift 代码后面的 xib 文件。

主页中的代码如下:

  import UIKit
import CoreData

class SepetViewController: UIViewController, UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate {

  @
  IBOutlet
  var sepetTable: UITableView!
    var barcodes: [CART] = []

  let managedObjectContext = (UIApplication.sharedApplication().delegate as!AppDelegate).managedObjectContext

  override func viewWillAppear(animated: Bool) {
    if let moc = self.managedObjectContext {


      var nib = UINib(nibName: "SepetTableCell", bundle: nil)
      self.sepetTable.registerNib(nib, forCellReuseIdentifier: "productCell")
    }
    fetchLog()
    sepetTable.reloadData()
  }

  func fetchLog() {

    if let moc = self.managedObjectContext {
      barcodes = CART.getElements(moc);
    }
  }



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

  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) - > UITableViewCell {


    let cell = tableView.dequeueReusableCellWithIdentifier("productCell") as ? SepetCell


    if cell == nil {
      println("cell nil")

    }



    let product: CART
    product = barcodes[indexPath.row]



    cell!.barcode ? .text = product.barcode
    cell!.name ? .text = product.name
    cell!.fav.tag = indexPath.row

    return cell!
  }

  func favorite(tag: Int) {



  }
}

当我单击 Cell 内的 fav 按钮时。 例如,我想将时间标签文本更改为任何内容。

当我点击 fav 按钮时,事件将转到 SepetCell.swift favoriteClicked(sender: UIButton) 函数。

因此,如果我尝试调用:SepetViewController().favorite(sender.tag)

它将进入

func favorite(tag: Int) {

      sepetTable.reloadData()

    }

但是 sepetTable 在它消失时为零。 我认为这是因为当我调用这个 SepetViewController().favorite(sender.tag) 函数时。 它首先创建 SepetViewController 类。 因此,由于未设置对象,它变得空了。

我怎样才能到达那个 sepetTable 或者什么是解决这个问题的最佳方法。

谢谢。

解决这个问题的流行模式是闭包和委托。 如果你想使用闭包,你可以这样做:

final class MyCell: UITableViewCell {
    var actionBlock: (() -> Void)? = nil

然后

    @IBAction func didTapButton(sender: UIButton) {
        actionBlock?()
    }

然后在您的 tableview 委托中:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) - > UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("MyCellIdentifier") as? MyCell
    cell?.actionBlock = {
       //Do whatever you want to do when the button is tapped here
    }

一种流行的替代方法是使用委托模式:

    protocol MyCellDelegate: class {
        func didTapButtonInCell(_ cell: MyCell)
    }

    final class MyCell: UITableViewCell {
        weak var delegate: MyCellDelegate?

然后

    @IBAction func didTapButton(sender: UIButton) {
        delegate?.didTapButtonInCell(self)
    }

.. 现在在您的视图控制器中:

然后在您的 tableview 委托中:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) - > UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("MyCellIdentifier") as? MyCell
    cell?.delegate = self

并添加对协议的一致性,如下所示:

extension MyViewController: MyCellDelegate {
    didTapButtonInCell(_ cell: MyCell) {
       //Do whatever you want to do when the button is tapped here
    }
}

希望这可以帮助!

上面的所有图案都很好 我的两分钱,如果你通过代码添加(例如多个不同的单元格等等),有一个简单的解决方案。

由于按钮允许指定“目标”,您可以在设置时直接将控制器和操作传递给单元格/按钮。

在控制器中:

let selector = #selector(self.myBtnAction)
setupCellWith(target: self, selector: selector)

...

在带有按钮的自定义单元格中:

final func setupCellWith(target: Any? selector: Selector){
       btn.addTarget(target, 
        action: selector,
       for: .touchUpInside)

}

凌晨 2 点回答:你想多了。 创建自定义 TableViewCell 类; 将原型单元类设置为您的新自定义类; 然后创建一个IBAction。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM