首页 > 解决方案 > 如何在我的 UITableViewCell 类的所有实例中访问模​​型类的一个特定实例的属性?

问题描述

我目前正在构建一个 iOS 应用程序,它的一个视图在 UITableView 的每一行内都包含一个 UICollectionView ,以便用户可以向下滚动整个视图,但也可以向右滚动每一行。例如,它看起来与 Spotify 主页一模一样。该应用程序的目的也是播放声音文件;当您单击这些集合视图单元格之一时,会播放声音。

为此,我创建了一个自定义 UITableViewCell 类。控制此视图的 UIViewController 将具有 IBOutlet 的类引用到包含那些自定义表格视图单元格的 UITableView,并且自定义 UITableViewCell 类将其内部的 UICollectionView 引用到该 UICollectionView 的 IBOutlet。然后我有另一个用于这些 UICollectionViewCells 的自定义类,只有在我的自定义 UITableViewCell 类中使用才有意义。

问题是我想在全球范围内知道是否有任何声音正在播放。但是,自定义 UITableViewCell 类的每个实例都会创建自己的模型实例,其中存在 isAnythingPlaying 属性,因此访问此属性只会告诉我当前 UITableViewCell 中是否有任何声音文件正在播放。为了清楚起见:

class Model {

    // (other properties would normally be here)

    var isAnythingPlaying: Bool = false

    // (other functions would normally be here)

    func getIsAnythingPlaying() {
    /*
    The problem with this method is that it will update a property (isAnythingPlaying)
    that needs to contain the same value no matter which cell of the table view 
    (CustomTableViewCell) is accessing it.

    This is just pseudocode for the real method, which works as intended.
    */

        if (somethingIsPlaying) {
            isAnythingPlaying = true
        }

        else {
            isAnythingPlaying = false
        }
    }
}

然后我的 CustomTableViewCell 类看起来像:

class CustomTableViewCell: UITableViewCell! {

    @IBOutlet weak var collectionView: UICollectionView!

    var customModel = Model!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        collectionView.delegate = self
        collectionView.dataSource = self

        customModel = Model()

    // (other functions would normally be here)

    }
}

extension CustomTableViewCell: UICollectionViewDelegate, 
  UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    ***************************************************************
    // at this point the value model.isAnythingPlaying will expectedly be different
    // for each instance of the UITableViewCell. If anything is playing within that
    // particular cell (row), it will be true; otherwise, false.
    ***************************************************************

}

有什么办法可以让所有 CustomTableViewCell 对象访问同一个 isAnythingPlaying 变量吗?我考虑将它放在捆绑包中的文本文件中,并让代码将文本文件从“真”切换为“假”,但这似乎太荒谬而无法实际尝试。

标签: iosswiftuitableview

解决方案


您可以使用static直接在Modelvia上设置的属性Model.isAnythingPlaying = true。将变量声明为静态会将属性放到类本身上,并确保该属性永远只有一个值。如果您想从模型的实例中引用静态变量,您可以像我在上面所做的那样引用类名或使用Self关键字,注意大写的“S”。

class Model {
    // static property that every instance can read/write by using Self.isAnythingPlaying
    // any object outside of the Model class can access the same value by
    // accessing the property on the class ex.  
    // if Model.isAnythingPlaying { 
    // }
    static var isAnythingPlaying: Bool = false

    func getIsAnythingPlaying() {
        return Self.isAnythingPlaying
    }
}

推荐阅读