我目前遇到了一个问题。我正在创建一个游戏,我希望能够使用 UITableView 来显示数据(比如关卡)。但是,我严格使用 SpriteKit,似乎无法让 UITableView 和 SpritKit 工作。
我尝试在名为“gameTableView”的“GameScene”类(它是一个 SKScene)中创建一个变量,并将其值设置为我创建的名为“GameRoomTableView”的类。
var gameTableView = GameRoomTableView()
该类的值为“UITableView”(请注意,我没有将其设置为 UITableViewController)。
class GameRoomTableView: UITableView {
}
我能够将 tableView 添加为我的 SKView 的 subview 。我在 GameScene 类中的“DidMoveToView”函数中执行了此操作。在其中得到 View 显示。
self.scene?.view?.addSubview(gameRoomTableView)
但是,我不知道如何更改部分数量以及如何添加单元格等内容。该类不允许我访问这些类型的内容,除非它是一个 viewController 并且我需要一个实际的 ViewController让它工作。我见过很多游戏都使用 tableView,但我不确定它们是如何让它工作的,哈哈。
请不要犹豫,告诉我我做错了什么,如果您知道更好的解决方法。如果您有任何问题,请告诉我。
最佳答案
通常我不喜欢像你那样子类化 UITableView
,我更喜欢使用 UITableView
委托(delegate)和数据源直接到我的 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()
}
}
输出:
关于ios - 在 Spritekit 中使用 UITableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41626348/