在Spritekit中使用UITableView

时间:2017-01-13 02:12:18

标签: ios swift uitableview sprite-kit

我目前遇到了问题。我正在创建一个游戏,我希望能够使用UITableView来显示数据(如级别)。但是,我严格使用SpriteKit,似乎无法使UITableView和SpritKit工作。

我尝试在我的GameScene'中创建一个变量。 class(这是一个SKScene)叫做' gameTableView'并且它的值设置为我称之为“GameRoomTableView'”的类。

var gameTableView = GameRoomTableView()

该课程的价值为' UITableView' (注意我没有将它设置为UITableViewController)。

class GameRoomTableView: UITableView {
}

我能够将tableView添加为我的SKView的子视图。我在我的'DidMoveToView'中做到了这一点。我的GameScene课程中的功能。在其中得到了展示的观点。

self.scene?.view?.addSubview(gameRoomTableView)

但是,我不知道如何更改部分的数量以及如何添加单元格。这个类不会让我访问那些类型的东西,除非它是一个viewController和那个我&# 39; d需要一个实际的ViewController来使它工作。我看过很多游戏都使用tableViews,但我不确定他们是如何让它工作的,哈哈。

请不要犹豫,告诉我我做错了什么,如果你知道更好的办法。如果您有任何问题,请告诉我。

1 个答案:

答案 0 :(得分:14)

通常我不喜欢UITableView的子类,我更喜欢直接使用UITableView委托和数据源到我的SKScene类来控制表规范和数据我的游戏代码。

但可能你有自己的个人计划,所以我举例说明你:

import SpriteKit
import UIKit
class GameRoomTableView: UITableView,UITableViewDelegate,UITableViewDataSource {
    var items: [String] = ["Player1", "Player2", "Player3"]
    override init(frame: CGRect, style: UITableViewStyle) {
        super.init(frame: frame, style: style)
        self.delegate = self
        self.dataSource = self
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // MARK: - Table view data source
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell
        cell.textLabel?.text = self.items[indexPath.row]
        return cell
    }
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return "Section \(section)"
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("You selected cell #\(indexPath.row)!")
    }
}
class GameScene: SKScene {
    var gameTableView = GameRoomTableView()
    private var label : SKLabelNode?
    override func didMove(to view: SKView) {
        self.label = self.childNode(withName: "//helloLabel") as? SKLabelNode
        if let label = self.label {
            label.alpha = 0.0
            label.run(SKAction.fadeIn(withDuration: 2.0))
        }
        // Table setup
        gameTableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        gameTableView.frame=CGRect(x:20,y:50,width:280,height:200)
        self.scene?.view?.addSubview(gameTableView)
        gameTableView.reloadData()
    }
}

<强>输出

enter image description here