确定在Swift中自定义listView单元格中按下的按钮

Oli*_*cer 6 listview objective-c uibutton swift

我在Swift中为listView创建了一个自定义单元格.它上面有两个按钮 - 一个是"暂停"按钮,另一个是"停止"按钮.我们的想法是每个订单项代表一个下载,因此用户可以独立停止和启动每个订单项.

但是,我需要为每个按钮创建一个@IBAction.我已经在主ViewController中创建了这些,当然,当它们被连接起来时,它们会触发相应的.

我坚持的位是识别按下哪一行按钮的标识符.我假设与cellForRowAtIndexPath有关的东西可行.

我找到了以下代码(我从类似的文本字段问题中找到):

@IBAction func startOrPauseDownloadSingleFile(sender: UIButton!) {
    let pointInTable: CGPoint = sender.convertPoint(sender.bounds.origin, toView: self.tableView)
    let cellIndexPath = self.tableView.indexPathForRowAtPoint(pointInTable)
}
Run Code Online (Sandbox Code Playgroud)

但是我不断收到错误'无法使用类型的参数列表调用'convertPoint'(@lvalue CGPoint,toView:$ T6)'.

有人可以帮忙吗?

谢谢,

Ima*_*tit 5

我把你的代码嵌入到一个简单的项目中。

在 Interface Builder 中,我创建了一个UITableViewController场景并将其类设置为“ViewController”。我向其中添加了一个UITableViewCell,将其标识符设置为“Cell”,将其样式设置为“Custom”,将其类设置为“CustomCell”。然后,我在单元格的 contentView 中添加了一个 UIButton,并为其设置了明确的自动布局约束。

在 Project Navigator 中,我创建了一个名为“ViewController”的新文件,并在其中添加了以下代码:

import UIKit

class CustomCell: UITableViewCell {

    @IBOutlet weak var button: UIButton!

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override init(style: UITableViewCellStyle, reuseIdentifier: String!) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
    }

    override func awakeFromNib() {
        super.awakeFromNib()
    }

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

}

class ViewController: UITableViewController {

    func buttonPressed(sender: AnyObject) {
        let pointInTable: CGPoint = sender.convertPoint(sender.bounds.origin, toView: self.tableView)
        let cellIndexPath = self.tableView.indexPathForRowAtPoint(pointInTable)
        println(cellIndexPath)
    }

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as CustomCell
        cell.selectionStyle = .None

        cell.button.addTarget(self, action: "buttonPressed:", forControlEvents: UIControlEvents.TouchUpInside)

        return cell
    }

}
Run Code Online (Sandbox Code Playgroud)

我最终将按钮链接IBOutletUIButtonInterface Builder,运行该项目,并能够从每个按钮触摸中记录相应单元格的索引路径。