ios - 如何在 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
}
}
我应该怎么办?
解决方案
问题在这里:
let myCity = CityCollection() // <-- this is the problem
myCity.delegate = self
您在这里所做的只是创建 CityCollection 类的新实例。您在下一行设置该实例的委托。然后... myCity
,您的 CityCollection 对象消失在一阵烟雾中。所以这两行是没用的。
您可能打算做的是以某种方式获取对已存在于界面中其他位置的现有CityCollection 对象的引用。
推荐阅读
- java - 从 spring 4.x 转移到 5.x 时出现 java.lang.NoClassDefFoundError
- curl - 在 Windows 上下载并解压缩存档
- docker - Docker compose up --force-recreate --build 使用缓存,但我不希望它这样做
- node.js - Foreach 应该等待下一次迭代,直到等待在节点中执行
- java - 错误:数据库错误,无法执行更新查询...语法错误:在第 1 行第 92 列遇到“S”
- java - 获取所有重复项
- elasticsearch - 读取 Logstash 日志但不会推送到 elasticsearch
- python - 使用 tensorflow 模型(更快的 rcnn)检测对象时,opencv dnn 的结果看起来很奇怪
- python - 创建GUI时如何在Python中创建下拉按钮并每次提取选择并将其分配给变量?
- ios - React Native Expo 应用程序在发布到 Testflight 时崩溃