swift - 从 model.swift 调用 viewController 函数
问题描述
我正在尝试GameplayViewController
通过移动可以移动到的内容来清理我的代码CurrentData.swift
。我有什么
GameplayViewController.swift
::
current = CurrentData.init(howManyRooms: rooms)
for index in 0...current!.items.count-1 {
if current!.firstLaunch {
createItems(imageName: current!.items[index].imageName)
}
}
它工作得很好。然后我有了将 for 循环移动到CurrentData.init
代码的想法
CurrentData.swift
:
init(howManyRooms: Int) {
self.size = Int(ceil(sqrt(Double(howManyRooms))))
for index in 0...items.count-1 {
if self.firstLaunch {
GameplayViewController.createItems(imageName: items[index].imageName)
}
}
}
我收到了这个错误:“实例成员 'createItems' 不能用于类型 'GameplayViewController';你是不是要使用这种类型的值?”
有没有一种值得的方式来调用GameplayViewController
func CurrentData.swift
?
这是函数本身:
public func createItems(imageName: String) {
let imageNamePNG = "\(imageName).png"
let itemImage = UIImage(named: imageNamePNG)
let itemImageView = UIImageView(image: itemImage)
if let freeSpace = self.freeSpace {
itemImageView.frame = CGRect(
x: Int.random(in: Int(freeSpace.minX) ... Int(freeSpace.maxX)),
y: Int.random(in: Int(freeSpace.minY) ... Int(freeSpace.maxY)),
width: 63, height: 63)
}
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
itemImageView.isUserInteractionEnabled = true
itemImageView.addGestureRecognizer(tapGestureRecognizer)
view.addSubview(itemImageView)
current?.createdImages.append(itemImageView)
}
解决方案
您应该考虑使用 UICollectionView 来完成您正在尝试做的事情。
您将在单元格中加载图像,并且当您点击单元格时有可用的委托方法,因此您不必担心设置手势等。
此外,查看模型视图控制器模式,以简洁的方式管理您的视图、数据和逻辑。数据不应该对视图有任何依赖。
推荐阅读
- sql - Oracle 数据库中的虚拟列
- xcode - 将 iPhone 8 适配到 iPhone 8 plus
- javascript - 如何使 addEventListener 同步
- android - Firebase - 应用程序被杀死时未收到推送通知 - Android 8
- ios - 如何修复不更新 UI 的目标 c 应用程序?
- kotlin - org.kodein.di.Kodein$NotFoundException: 没有为绑定找到绑定
() 和 ? ().? { ? } - javascript - 我想基于 JSON 对象在 mxGraph 中添加圆角矩形
- reactjs - 为什么 React 让我的 SVG 形状颜色看起来很奇怪?
- python - 如何在 python 中显示来自 sql 的值,并使用我在 ReactJS 中的 UI 设计显示它?
- mysql - 加载网页后Nodejs-Mysql查询得到结果,这给出了未定义的错误