首页 > 解决方案 > 如何在 swift 中在 nib 类之间使用协议委托?

问题描述

我有一个视图控制器,它有两个 nib 文件的子视图。我的第一个 nib 名称是 citycollection,第二个是 currentxib,它们都是 UIVIEW。在 citycollection 视图中,当我单击其中的项目时,我有我想要的 collectionview,在 currentxib 类的标签中打印我通过协议发送的数据。(注意它们都是 UIView 而不是视图控制器。)但它不起作用。我的主视图控制器类仍然是空的。这是我的代码:

CityCollection 类:

///// CityCollection

class CityCollection: UIView, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    weak var delegate: sendDataDelegate?

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        let fName = Publics.instance.getCities()[indexPath.row].fName

        delegate?.name(data: fName)

    }

}



protocol sendDataDelegate : NSObjectProtocol {
    func name(data : String)
}

CurrentXib 类:

////CurrentXib
class CurrentXib: UIView, sendDataDelegate {


    func name(data: String) {
        lblCityName.text = data
    }


    @IBOutlet weak public var lblCityName: UILabel!



    override func awakeFromNib() {

        let myCity = CityCollection()
        myCity.delegate = self
    }
}

我应该怎么办?

标签: iosswift

解决方案


问题在这里:

    let myCity = CityCollection() // <-- this is the problem
    myCity.delegate = self

您在这里所做的只是创建 CityCollection 类的新实例。您在下一行设置该实例的委托。然后... myCity,您的 CityCollection 对象消失在一阵烟雾中。所以这两行是没用的。

您可能打算做的是以某种方式获取对已存在于界面中其他位置的现有CityCollection 对象的引用。


推荐阅读