gpt4 book ai didi

objective-c - 识别在 Swift 中的自定义 listView 单元格中按下的按钮

转载 作者:搜寻专家 更新时间:2023-10-30 22:14:27 25 4
gpt4 key购买 nike

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

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

有人能帮忙吗?

谢谢,

最佳答案

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

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

}

我最终将按钮的 IBOutlet 链接到 Interface Builder 中的 UIButton,运行项目并能够记录每个按钮触摸的相应单元格的 indexPaths。

关于objective-c - 识别在 Swift 中的自定义 listView 单元格中按下的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25611634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com