ios - 从 Swift 中的另一个类访问一些值

标签 ios swift uitableview

我有一个像这样的 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/

相关文章:

ios - Firebase 登录的授权错误列表

iphone - 为表格 View 中的单元格设置可变高度

ios - 修复覆盖函数 viewDidAppear

ios - 使用 Swift 将 NSString 转换为 CLLocationCoordinate2DMake

ios - UIView 高度变化未反射(reflect)在 UI 中

ios - 如何在 Swift 中将 UITableView 的单元格文本设置为数据库单元格的内容?

iphone - 在什么情况下我必须将代码放入 -beginUpdates -endUpdates block 中,什么时候它是可选的?

ios - 不允许创建操作

ios - 强制停止后将位置设置为 SKSpriteNode(即设置速度 0)

ios - 在 ios 中如何在后台执行具有 NSData 返回类型的方法