首页 > 解决方案 > 从 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';你是不是要使用这种类型的值?”
有没有一种值得的方式来调用GameplayViewControllerfunc 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)
    }

标签: swiftxcode

解决方案


您应该考虑使用 UICollectionView 来完成您正在尝试做的事情。

您将在单元格中加载图像,并且当您点击单元格时有可用的委托方法,因此您不必担心设置手势等。

此外,查看模型视图控制器模式,以简洁的方式管理您的视图、数据和逻辑。数据不应该对视图有任何依赖。


推荐阅读