I'm currently having an issue. I'm creating a game and I want to be able to use a UITableView to show data (Like levels). However, I'm using strictly SpriteKit and can't seem to get the UITableView and SpritKit to work.
I tried creating a variable in my 'GameScene' class (which is an SKScene) called 'gameTableView' and its value set to a class I made called 'GameRoomTableView'.
var gameTableView = GameRoomTableView()
The class had the value of 'UITableView' (notice that I did not set it to UITableViewController).
class GameRoomTableView: UITableView {
}
I was able to add the tableView as a subview of my SKView. I did this in my 'DidMoveToView' function that's inside my GameScene class. In which got the view to show.
self.scene?.view?.addSubview(gameRoomTableView)
However, I do not know how to change things like the number of sections and how to add cells.The class won't let me access those type of things unless it's a viewController and with that I'd need an actual ViewController to get it to work. I've seen many games use tableViews but I'm not sure how they got it to work, haha.
Please don't hesitate to tell me what I'm doing wrong and if you know of a better way of going about this. Let me know if you have any questions.
Usually I don't prefer subclass the UITableView as you doing, I prefer to use the UITableView delegate and datasource directly to my SKScene class to control both table specs and data to my game code.
But probably you have your personal scheme so I make an example to you follow your request:
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()
}
}
Output:
Related
I have parsing the JSON values in UITableView using MVC pattern, For that, I have created a separate UITableView swift class, Model class, and UIViewController class as well.
I can able to parse the JSON values into the table view. But the problem is I can't able to pass the selected tableView cell values to my controller using the delegate method
Here my code is
UIVIewController :
class ViewController: UIViewController,contactSelectionDelegate {
var contactArray = [Address]()
#IBOutlet weak var userTable: UserTable!
let user = UserTable()
override func viewDidLoad() {
super.viewDidLoad()
user.userdelegate? = self
if Connectivity.isConnectedToInternet() {
print("Yes! Network connection is available")
APIManager.sharedInstance.fetchUserDetails(urlString: FETCH_USER_DETAIL_URL, userCount: ["offset":1]) { connectionResult in
switch connectionResult {
case .success(let data):
do {
self.contactArray = try JSONDecoder().decode([Address].self, from: data)
print(self.contactArray.count)
print(self.contactArray[0].Name)
DispatchQueue.main.async {
print(self.contactArray)
self.userTable.dataSourceArray=self.contactArray
self.userTable.reloadData()
}
}
catch let errorValue {
print(errorValue)
}
case .failure(let error):
print(error)
}
}
}
else{
print("No network connection")
}
}
func selectedUserContact(name: String, email: String, phone: String) {
print("Delegate Called")
let userdetailVC = storyboard?.instantiateViewController(withIdentifier: "UserContactDetailPage") as! UserContactDetailPage
userdetailVC.name = name
userdetailVC.email = email
userdetailVC.phone = phone
self.navigationController?.pushViewController(userdetailVC, animated: true)
} }
UITableView :
protocol contactSelectionDelegate: class{
func selectedUserContact(name: String ,email: String ,phone: String)
}
class UserTable: UITableView ,UITableViewDelegate ,UITableViewDataSource {
var dataSourceArray = [Address]()
weak var userdelegate: contactSelectionDelegate?
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
self.delegate=self
self.dataSource=self
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1;
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataSourceArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UserCell = tableView.dequeueReusableCell(withIdentifier: "UserCell", for: indexPath) as! UserCell
if self.dataSourceArray.count>0 {
let myUser = self.dataSourceArray[indexPath.row]
cell.nameLbl.text = myUser.Name
cell.emailLbl.text = myUser.Email
cell.phoneLbl.text = myUser.Phone
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 200
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let myUser = self.dataSourceArray[indexPath.row]
print(myUser.Name)
print(myUser.Email)
print(myUser.Phone)
userdelegate?.selectedUserContact(name: myUser.Name, email: myUser.Email, phone: myUser.Phone)
}}
Here when I click table on the tableView cell didSelectRowAtIndexPath method called but selectedUserContact not getting called.
You've misunderstood the purpose of delegating here. The idea is that your table view is only responsible for drawing a table, it shouldn't be responsible for maintaining any of the data that it's displaying. This allows you to cleanly design your code using the Model-View-Controller (MVC) paradigm. Delegation allows your controllers to pass model information to the views without breaking MVC.
In your example: Address is the model, the table view is the view, and your view controller is the controller. So you want your controller to conform to the table view's delegate/data source protocols so that it can feed the data to it correctly.
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var contactArray = [Address]()
#IBOutlet weak var userTable: UserTable!
override func viewDidLoad() {
super.viewDidLoad()
if Connectivity.isConnectedToInternet() {
print("Yes! Network connection is available")
APIManager.sharedInstance.fetchUserDetails(urlString: FETCH_USER_DETAIL_URL, userCount: ["offset":1]) { connectionResult in
switch connectionResult {
case .success(let data):
do {
self.contactArray = try JSONDecoder().decode([Address].self, from: data)
print(self.contactArray.count)
print(self.contactArray[0].Name)
DispatchQueue.main.async {
print(self.contactArray)
self.userTable.reloadData()
}
}
catch let errorValue {
print(errorValue)
}
case .failure(let error):
print(error)
}
}
}
else{
print("No network connection")
}
}
// MARK: - UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 1;
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.contactArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UserCell = tableView.dequeueReusableCell(withIdentifier: "UserCell", for: indexPath) as! UserCell
let myUser = self.contactArray[indexPath.row]
cell.nameLbl.text = myUser.Name
cell.emailLbl.text = myUser.Email
cell.phoneLbl.text = myUser.Phone
return cell
}
// MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 200
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let myUser = self.contactArray[indexPath.row]
print(myUser.Name)
print(myUser.Email)
print(myUser.Phone)
selectedUserContact(name: myUser.Name, email: myUser.Email, phone: myUser.Phone)
}
// MARK: -
func selectedUserContact(name: String, email: String, phone: String) {
print("Delegate Called")
let userdetailVC = storyboard?.instantiateViewController(withIdentifier: "UserContactDetailPage") as! UserContactDetailPage
userdetailVC.name = name
userdetailVC.email = email
userdetailVC.phone = phone
self.navigationController?.pushViewController(userdetailVC, animated: true)
}
}
EDIT: I just want to add that you need to make sure in your storyboard that you set ViewController as the delegate and dataSource of the table view. Then you can remove all the code that you've written in the UserTable class. If anything you don't need it at all and your table view can be a simple UITableView. I almost never create subclasses of it, since you can normally do everything through the delegation and UITableViewCell subclasses.
Looks like you're instantiating the table view from a storyboard, so you're not setting the delegate on the correct instance of UserTable (and the delegate method is never called because the delegate is nil).
In the view controller change
user.userdelegate? = self
to
userTable.userdelegate? = self
According to this line, Your have a table view in the storyboard and taken outlet in viewcontroller.
#IBOutlet weak var userTable: UserTable!
So you don't need to do this like that:
let user = UserTable()
You have to give delegate like this:
userTable.userdelegate? = self
For mine it is working fine with the below scenario. Kindly check with that one.
UserTable
#objc protocol contactSelectionDelegate: class {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
}
weak var userdelegate: contactSelectionDelegate?
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
delegate?.tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
}
ViewController
class ViewController: UIViewController {
}
extension ViewController: contactSelectionDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// YOU CAN GET THE ALL THE STUFFS WHICH IS USER SELECTED IN THE TABLE VIEW
}
}
No data is appearing in my Swift table. I'm fairly new to Swift and not quite sure why this or what I might be missing. I followed the guide here for the most part with some differences:
Apple Table Creation
Here's the tableView definition:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "AccountTableViewCell"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? AccountTableViewCell else {
fatalError("The dequeued cell is not an instance of AccountTableViewCell.")
}
let item = userDataSource[indexPath.row]
// Dummy values just to test this out
cell.leftLabel.text = "test1";
cell.rightLabel.text = "test2";
return cell
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1;
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) ->Int {
return userDataSource.count;
// This should be an array value, but I have also tried passing a static int here as well to test
}
Here is my class definition with the implemented procotols:
class AccountViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
And here is my table cell definition:
class AccountTableViewCell: UITableViewCell {
//MARK: Properties
#IBOutlet weak var leftLabel: UILabel!
#IBOutlet weak var rightLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
I've got both rightLabel and leftLabel setup in the Storyboard.
I can go to the account page represented by this view controller and a table display does come up - it just has absolutely no data in it.
What am I missing?
It is not sufficient to simply add a UITableView to your view controller scene. You must set the tableview's dataSource property to your view controller instance in the Storyboard connections inspector for the tableview.
I created a UITableView in a UIViewController from the storyboard and create custom tableViewCell class. Now when I run my project,
It is not scrolling when I touch any cell and move up/down.
BUT, it scrolls if I start scrolling with the either end of UItableViewCell (nearly, 15px of left inset).
I tried to create another fresh tableView, still not working.
I tried to create a tableViewController, still not working.
Then I think the code is NOT the cause of the issue.
Using Xcode 8.2.1
Below is my code work :
Class File
struct Quote {
var text: String
}
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet var tableView: UITableView?
let cellIdentifier = "cell"
// Array of strings for the tableView
var tableData = [Quote(text: "zadz ad azd azds fsd gdsfsd"), Quote(text: "zakd gqsl jdwld bslf bs ldgis uqh dm sd gsql id hsqdl sgqhmd osq bd zao mos qd"), Quote(text: "azdhsqdl sb ljd ghdlsq h ij dgsqlim dhsqihdùa dbz ai ljsm oqjdvl isq dbvksqjld"), Quote(text: "dsqb jhd gs qdgsq dgsq u hdgs qli hd gsql i dgsq li dhs qij dhlqs dqsdsd.")]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView?.register(UITableViewCell.self, forCellReuseIdentifier: self.cellIdentifier)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return number of rows in table
return tableData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Create Resusable Cell, get row string from tableData
let cell = tableView.dequeueReusableCell(withIdentifier: self.cellIdentifier)! as! cellClass
let row = indexPath.row
// Set the labels in the custom cell
cell.mainText.text = tableData[row].text
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Do what you want here
let selectValue = self.tableData[indexPath.row]
print("You selected row \(indexPath.row) and the string is \(selectValue)")
}
}
And this is my cellClass: (Custom cell)
class cellClass: UITableViewCell {
#IBOutlet weak var mainText: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
Storyboard hierarchy of UITableView
You might be have some x-code issues because generally it never happens and I run your project it working properly as usually it works.
Below is code work I have done.
I'm not taking sturcture of array like you, I'm just doing with taking simple array.
my array is
arrayData = ["One", "Two", "three", "four"]
below is cellForRow
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : cellClass = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! cellClass
cell.lblstates.text = arrayData[indexPath.row]
return cell
}
If you facing any issue then let me know.
Check if the user interaction Enabled check of your cell is off or not in the storyboard
Resolved: I had to uninstall and install Xcode again..
var leadername = ["1","2","3","4"]
var districts = ["Delhi","Kerala"]
override func viewDidLoad() {
leadTableSetup()
super.viewDidLoad()
}
func leadTableSetup(){
LeadTableView.delegate = self
LeadTableView.dataSource = self
self.LeadTableView.register(UINib(nibName: "LeaderBoardTableViewCell", bundle: nil), forCellReuseIdentifier: "leadCell")
}
func numberOfSections(in tableView: UITableView) -> Int {
return 5
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 14
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "leadCell") as! LeaderBoardTableViewCell
// Set text from the data model
cell.areaLbl.text = districts[indexPath.row]
cell.leaderNameLbl.text = leadername[indexPath.row]
return cell
}
I have declared two strings and I need to display these strings in the labels in my custom collection view cell that I have created. How can I achieve this? I need to display "leadername" string in one label and "districts" label in another label.
Go with this demo, Shared Demo
After the demo, If you still face any problem then let me know.
Now Listen Here
I think you need output something like this,
Follow the steps: -
Create a new viewcontroller(says, CustomTableVC) in your storyboard and one UITableView(give constraints and delegate to its own class), take outlet of UItableView (says, tblMyCustom)
Now press CLT+N for new file and do like this below image, Subclass - UItableViewCell and also tick on XIB option.
Open our xib file, add new UIView (says myView, as you see highted in below image), in this myView add two labels
Now take outlet of these two labels in its customCell class
class CustomTableCell: UITableViewCell {
#IBOutlet var lblLeaderNo: UILabel!
#IBOutlet var lblDistict: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
Now back to your Viewcontroller Class
import UIKit
class CustomTableVC: UIViewController , UITableViewDelegate, UITableViewDataSource{
#IBOutlet var tblMyCustom: UITableView!
var leaderno : [String]!
var distict : [String]!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.tblMyCustom.register(UINib(nibName: "CustomTableCell", bundle: nil), forCellReuseIdentifier: "customCell")
self.leaderno = ["1", "2", "3", "4"]
self.distict = ["Delhi","Kerala", "Haryana", "Punjab"]
// above both array must have same count otherwise, label text in null
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return leaderno.count;
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
var customCell: CustomTableCell! = tableView.dequeueReusableCell(withIdentifier: "customCell") as? CustomTableCell
customCell.lblLeaderNo.text = self.leaderno[indexPath.row]
customCell.lblDistict.text = self.distict[indexPath.row]
return customCell
}
}
above all is code of VC, it is not getting settle down here in single code format, I dont know why.
Now, follow these steps you get output as i show you image in starting of the procedure.
I am creating iOS app with swift for the iPad. There is going to be table view for every view and I created a UITableView class but I cannot able to view any data. I have already linked the tableview inside other views to that custom class already.
import UIKit
class SideTable: UITableView, UITableViewDataSource, UITableViewDelegate {
var TableItems = ["...", "Dashboard"]
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TableItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = dequeueReusableCell(withIdentifier: TableItems[indexPath.row])! as UITableViewCell
cell.textLabel?.text = TableItems[indexPath.row]
cell.textLabel?.numberOfLines = 0
cell.textLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
// let currentpagetitle = self.navigationItem.title?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
let cellname = cell.reuseIdentifier?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
// if (cellname == currentpagetitle)
// {
//
// cell.backgroundColor = UIColor.lightGray
// }
//
return cell
}
Did you connect the data source and delegate?
put in your viewwilllappear, for example (or viewDidLoad):
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.tableview.datasource = self
self.tableview.delegate = self
}
Or connect it if you are using Storyboard or Xib
Control + click over tableview and connect with owner, then selecte delegate and repeat for data source
If this is not the problem, maybe you have a problem with the definition of the cell. Change your dequeueCell:
let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as UITableViewCell
Use the same identifier if the cell are similar. Now you are using different names, you are using TableItems[indexPath.row] for each cell