如何在Swift中在UITableViewCell上添加一个带有click事件的按钮?

ct3nt3jp  于 2023-08-02  发布在  Swift
关注(0)|答案(5)|浏览(114)

在我的主页中,我为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
    }
}

字符串
这是我的xib文件背后的代码为. swift。
在主页面的代码喜欢下面:

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


  }
}


当我点击最喜欢的按钮内的细胞。例如,我想将时间标签文本更改为任何内容。
当我点击fav按钮时,事件将转到SepetCell。swift favoriteClicked(sender:UIButton)功能。
所以如果我试着打电话:SepetViewController().favorite(sender.tag)
它将进入

func favorite(tag: Int) {

      sepetTable.reloadData()

    }


但是sepetTable在那里时为nil。我想这是因为当我调用这个SepetViewController().favorite(sender.tag)函数时。它首先创建SepetViewController类。因此,由于对象未设置,它将变为null。
我如何才能到达那个sepetTable或者解决这个问题的最佳方法是什么。

  • 谢谢-谢谢
vcudknz3

vcudknz31#

解决这个问题的常用模式是闭包和委托。如果您想使用闭包,可以执行如下操作:

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


希望这对你有帮助!

xyhw6mcr

xyhw6mcr2#

上面所有的图案都很好。我的两分钱,如果你添加代码(例如多个不同的细胞等..)有一个FAR简单的解决方案。
由于按钮允许指定一个“目标”您可以直接传递控制器和操作到单元格/按钮时设置它。
在控制器中:

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

字符串
...
在带有按钮自定义单元格中:

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

}

svmlkihl

svmlkihl3#

为该按钮添加目标。

button.addTarget(self, action: #selector(connected(sender:)), for: .touchUpInside)

字符串
设置该按钮的标签,因为您正在使用它。

button.tag = indexPath.row


通过子类化UITableViewCell来实现这一点。按钮,通过插座连接。
要获取连接函数中的标记:

@objc func connected(sender: UIButton){
    let buttonTag = sender.tag
}

3wabscal

3wabscal4#

extension ViewController: UITableViewDelegate, UITableViewDataSource {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    let cell = UITableViewCell()
    
    //cell.buttonPressed add in Your tableViewCell file
    
    cell.buttonPressed = { [self] in
        print("Cell")
    }
}

字符串

一月一日

var buttonPressed : (() -> ()) = {}

   @IBAction func btnclick(_ sender: Any) {
        buttonPressed()
    }

l0oc07j2

l0oc07j25#

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

相关问题