我有一个像这样的 TableViewCell 类:
class CampaignsTableViewCell: UITableViewCell {
@IBOutlet weak var activateButton: UIButton!
@IBOutlet weak var titleCampaignPlaceholder: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
setUpButton()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
private func setUpButton(){
activateButton.backgroundColor = .clear
activateButton.layer.cornerRadius = 5
activateButton.layer.borderWidth = 1
activateButton.layer.borderColor = UIColor.blue.cgColor
}
}
并且,在另一个 ViewController 类中,我有我的 UITableView 方法:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let rowNumber = indexPath.row
let cellIdentifier = "CampaignTableViewCell"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? CampaignsTableViewCell else {
fatalError("The dequeued cell is not an instance of TableViewCellController.")
}
cell.titleCampaignPlaceholder.text = campaignsArray[rowNumber].campaignName
return cell
}
我需要在我的 UITableView 方法中使用我的 activateButton 才能访问 campaignsArray。我有另一种方法需要该数组的值,所以我需要每次从我的 UITableView 中按下 activateButton 时调用该方法。
有什么想法吗? 非常感谢
最佳答案
在 UITableViewCell 中有一个按钮的情况下,我喜欢做的事情如下:
给单元格一个闭包,当像这样点击按钮时调用该闭包
class CampaignsTableViewCell: UITableViewCell {
... all your code....
// give your cell a closure that is called when the button is pressed
var onButtonPressed: ((_ sender: UIButton) -> ())?
@IBAction func buttonPressed(sender: UIButton) { // wire that one up in IB
onButtonPressed?(sender)
}
}
然后在您的 TableViewController 中
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! CampaignsTableViewCell
cell.titleCampaignPlaceholder.text = campaignsArray[rowNumber].campaignName
cell.onButtonPressed = { [weak self] sender in
// Do your magic stuff here
}
return cell
希望对你有帮助
关于ios - 从 Swift 中的另一个类访问一些值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45332680/