I took an UIViewController. Then brought a TableView into it. And then a TableViewCell in the tableview. I assigned identifier and custom table view cell class with that prototype cell. Also created necessary outlets. Then this is my parent view controller:
class MyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var theTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// let cell = MyTableViewCell()
// cell.optionText = UILabel()
// cell.optionText?.text = "testing..."
// theTableView.addSubview(cell)
theTableView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! MyTableViewCell
cell.optionText.text = "hello..."
return cell
}
}
But my table is empty. What am I missing?
You have to add the following line in your viewDidLoad:
theTableView.dataSource = self
When you do that, you provide dataSource to your Tableview from your ViewController and then your TableView starts showing data.
The methods cellForRowAtIndexPath and rowsForSection are both Datasource methods. Since you haven't set your dataSource that's why your TableView fails to load the provided data.
Also if you haven't added the TableView via Storyboard/Xib, you also have to add it as a subview of your view.
Related
I have a normal view controller with a table view inside, so the class is just a normal UIViewController, therefor I am unable to call self.tableView with this.
I have an asynchronous call to create an array of Aircraft objects that is taken from an online database, but that is only completed after the table cells are initially loaded. I am trying to update the table cells after this asynchronous call is completed, but am unsure how to do so.
I do the async call in viewDidLaod(). Here is my current code that only displays the loading tags since the update has not taken place for the aircraft array.
class AircraftViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let log = Logger( id: String(AircraftViewController.self) )
let dvc = DownloadViewController()
var aircraftArr = [Aircraft]()
override func viewDidLoad() {
super.viewDidLoad()
dvc.getMobileSystemOverviewHTML {
dispatch_async(dispatch_get_main_queue()){
self.aircraftArr = self.dvc.aircraft
self.log.debug("\n\n\n\n\n \(self.aircraftArr) \n\n\n\n\n")
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table View Delegate Methods
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("AircraftCell", forIndexPath: indexPath) as! AircraftCell
if indexPath.row < aircraftArr.count{
let singleAircraft = aircraftArr[indexPath.row] as Aircraft
cell.aircraft = singleAircraft
} else {
cell.aircraft = Aircraft(tailID: "Loading", aircraftSN: "Loading", Box_SN: "Loading")
}
return cell
}
You need to create the outlet of tableview like this
#IBOutlet var tableView: UITableView!
After that reload this tableview in your dispatch_async
dvc.getMobileSystemOverviewHTML {
dispatch_async(dispatch_get_main_queue()){
self.aircraftArr = self.dvc.aircraft
self.tableView.reloadData()
self.log.debug("\n\n\n\n\n \(self.aircraftArr) \n\n\n\n\n")
}
}
Hope this will help.
I need to pass data from one view controller to another view controller. I used segue (detail) and define a model class named as "Photo".
TableViewController looks like the following:
var photos = [Photo]() //strongly typed swift array
override func viewDidLoad() {
super.viewDidLoad()
var newPhoto = Photo(name:"cat ", fileName:"cat", notes:"cat_file")
photos.append(newPhoto)
var newPhoto2 = Photo(name:"r2 ", fileName:"r2", notes:"r2")
photos.append(newPhoto2)
}
And the other view controller (DetailViewController) looks like the following:
import UIKit
class PhotoDiplayViewController: UIViewController {
var currentPhoto: Photo?
#IBOutlet weak var currentImage: UIImageView!
#IBOutlet weak var currentLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
var image = UIImage(named: currentPhoto!.fileName)
self.currentImage.image = image
self.currentLabel.text = currentPhoto?.name
println(currentPhoto!.name + currentPhoto!.fileName + currentPhoto!.notes)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
When I am running the program, the table view is loading fine and if i click on any cell it is going to the detail view controller. but noting is there in the detail view controller. And I used println() to check and the output is coming in the debugger like the following:
cat cat cat_file
To pass data, I used the following segue code block:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
var secondScene = segue.destinationViewController as! PhotoDiplayViewController
if let indexPath = self.tableView.indexPathForSelectedRow(){
let selectedPhoto = photos[indexPath.row]
secondScene.currentPhoto = selectedPhoto
}
}
But still no luck! Tried to figure out where I am missing? Can anybody tell me where I am lagging?
UPDATE: complete detail view controller class code
UPDATE: Full detail of My table view code
import UIKit
class PhotoTableViewController: UITableViewController {
var photos = [Photo]() //strongly typed swift array
override func viewDidLoad() {
super.viewDidLoad()
var newPhoto = Photo(name:"cat ", fileName:"cat", notes:"cat_file")
photos.append(newPhoto)
var newPhoto2 = Photo(name:"r2 ", fileName:"face.jpg", notes:"r2")
photos.append(newPhoto2)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return photos.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("photoCell", forIndexPath: indexPath) as! UITableViewCell
var currentPhoto = photos[indexPath.row]
cell.textLabel?.text = currentPhoto.name
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
var secondScene = segue.destinationViewController as! PhotoDiplayViewController
if let indexPath = self.tableView.indexPathForSelectedRow(){
let selectedPhoto = photos[indexPath.row]
secondScene.currentPhoto = selectedPhoto
}
}
}
Don't use a segue. Use this, its easier.
Follow these steps...
1: Create a Separate file called Manager.swift and place this code in it...
//manager.swift
import Foundation
struct Manager {
static var dataToPass = String()
}
2: Clean your project by pressing Shift+Command+K.
3: In the first view controller set the dataToPass to the data you want to pass...
Manager.dataToPass = self.dataToPass
4: In the second view controller retrieve the data and set the content to the dataToPass...
self.dataToReceive = Manager.dataToPass
5: Your Finished!!
The code which I presented is working fully after deleting all the image view and label from the storyboard and remapping. But I am wondering what was the problem. However, I want to share one screen shot:
In the screen shot, you will see 3 components: 2 labels and 1 image view. One 1 label's text is dark black colored but the for the other 2 it's not alike them. All of them are properly configured.
Still I don't know why this happens? I am not sure .... is it possible to add some hidden components on the top of storyboard??? or is it a bug of Xcode????
However, if you have similar experience please share. My aim is not only solve the problem but also to understand the cause of the problem.
:)
I am new to Swift, and iOS development in general. I am attempting to create a custom UITableViewCell. I have created the cell in my main storyboard on top of a UITableView that is inside a UIViewController. When I loaded one of the default cells, I was able to populate it with data. However, now that I am using a custom cell, I cannot get any data to appear in the table. I have gone through all kinds of tutorials and questions posted on the internet, but I can't figure out why it is not working. Any help would be appreciated.
Here is my code for the UIViewController that the tableview resides in.
import UIKit
class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tblView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//self.tblView.registerClass(UITableViewCell.self, forCellReuseIdentifier : "Cell")
self.tblView.registerClass(CustomTableViewCell.self, forCellReuseIdentifier : "Cell")
tblView!.delegate = self
tblView!.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataMgr.data.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : CustomTableViewCell = self.tblView.dequeueReusableCellWithIdentifier("Cell", forIndexPath : indexPath) as! CustomTableViewCell
var values = dataMgr.data[indexPath.row]
cell.newTotalLabel?.text = "\(values.newTotal)"
cell.winLoseValueLabel?.text = "\(values.newTotal - values.currentTotal)"
cell.dateLabel?.text = "5/17/2015"
return cell
}
}
I have stepped through the program where it is assigning values to the cell variables. The variable 'values' is being populated with data, but when stepping over the assignment lines to the cell variables, I found that they are never assigned. They all remain nil.
When you make a custom cell in the storyboard, don't register the class (or anything else). Just be sure to give the cell the same identifier in the storyboard that you pass to dequeueReusableCellWithIdentifier:forIndexPath:.
I am learning Swift and I have pattern that I used to do in Objective C, but don't understand how to do it here.
I have UIViewController with TableView. I works fine when I put my array inside it. But according to MVC I want to move my array with data to another class. And I have no idea how to do it. Everything I tried doesn't work.
Thank you!
My code, how to move tableDS outside:
import UIKit
class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
//temp table data
let tableDS = ["fdf", "dfd"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableView.delegate = self
tableView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableDS.count
}
let textCellIdentifier = "TableViewCell"
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: MyCell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) as MyCell
let row = indexPath.row
cell.dayLabel.text = tableDS[row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let row = indexPath.row
println(tableDS[row])
}
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
cell.textLabel.text = tableDS[indexPath.row]
return cell
}
This should work.
If you want to use the MVC pattern, create a new singleton class, create the array there, then create a method returning the array.
First you need to initialize your table view with an empty array. When you load your MyViewController from another view controller in the code example below you can pass your data, and change your let tableDS = [“fdf”, “dfd”] to var tableDS = [“fdf”, "dfd"]. let is used for a constant variables.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "YourMyViewControllerSequeId" {
let myViewController = segue.destinationViewController as MyViewController
var myArrayToPass = ["learn swift", "or get a life"];
myViewController.tableDS = myArrayToPass
myViewController.tableView.reloadData()
}
}
In the MVC design pattern for a table view the table view is the view object. The controller is the view controller.
The model is whatever you use to store your data.
The controller object serves as an intermediary between the model and the view.
For a simple table view the model object can be a as simple as an array. The array is the model. Thus there is no reason to store the data in a separate object.
If you really want to make your model a completely different object, create a new class. Call it MyTableViewModel. Make your MyTableViewModel class contain an array of your data. Also make MyTableViewModel conform to the UITableViewDatasource protocol. To do that, you'll have to implement several methods - in particular, cellForRowAtIndexPath.
Now in your view controller, create a MyTableViewModel object as a strong property of your view controller, install the array in it, and make it the data source of the table view.
Done.
Again, though, it's quite common to just treat a simple array as your model, and let the view controller serve up cells by implementing cellForRowAtIndexPath in the view controller.
I am trying to load a list of titles from reddit.com/.json, but my tableview under a UIViewController would not load data whenever I launch it, the screen would be blank like this:
http://imgur.com/ucriMht
I have to click the Downloads Tab and then click back to the Current Sub tab in order for my TableView to properly load data from the json file:
http://imgur.com/TJyW65O
I also attach my code of the ViewController for that tab in this question to see if anyone can spot where I have done wrong.
import UIKit
class CurrentSubViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,NSURLConnectionDelegate,UISearchBarDelegate {
var manager:DataManager = DataManager()
var localJson:JSON=JSON.nullJSON
#IBOutlet var tableView : UITableView!
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
manager.startConnection()
print("subredditview loaded")
// Do any additional setup after loading the view.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return manager.json["data"]["children"].count
}
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = self.tableView?.dequeueReusableCellWithIdentifier("TitleCell",forIndexPath:indexPath) as UITableViewCell
let row=indexPath.row
print("got here /table view yeah")
cell.textLabel?.text = manager.json["data"]["children"][row]["data"]["title"].stringValue
cell.detailTextLabel?.text = manager.json["data"]["children"][row]["data"]["author_name"].stringValue
/**if !json["data"]["children"][row]["data"]["thumbnail"].stringValue.isEmpty
{
let thumbnailPath=json["data"]["children"][row]["data"]["thumbnail"].stringValue
let thumbnailURL:NSURL=NSURL(string: thumbnailPath)!
let thumbnailData=NSData(contentsOfURL:thumbnailURL)
let thumbnail=UIImage(data:thumbnailData!)
cell.imageView?.image=thumbnail
}**/
return cell
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
manager.query="http://reddit.com/r/"+searchBar.text+"/.json"
manager.data=NSMutableData()
manager.startConnection()
tableView?.reloadData()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
one way to solve this problem is start the networkActivityIndicator when data is receive from the server this way:
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
after that when data is received you can set network activity to false and when the network activity is done you can reload your tableView this way:
if UIApplication.sharedApplication().networkActivityIndicatorVisible == false{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})
}
and your code will be something like this:
import UIKit
class CurrentSubViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,NSURLConnectionDelegate,UISearchBarDelegate {
var manager:DataManager = DataManager()
var localJson:JSON=JSON.nullJSON
#IBOutlet var tableView : UITableView!
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
manager.startConnection()
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
print("subredditview loaded")
// Do any additional setup after loading the view.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return manager.json["data"]["children"].count
}
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = self.tableView?.dequeueReusableCellWithIdentifier("TitleCell",forIndexPath:indexPath) as UITableViewCell
let row=indexPath.row
print("got here /table view yeah")
cell.textLabel?.text = manager.json["data"]["children"][row]["data"]["title"].stringValue
cell.detailTextLabel?.text = manager.json["data"]["children"][row]["data"]["author_name"].stringValue
/**if !json["data"]["children"][row]["data"]["thumbnail"].stringValue.isEmpty
{
let thumbnailPath=json["data"]["children"][row]["data"]["thumbnail"].stringValue
let thumbnailURL:NSURL=NSURL(string: thumbnailPath)!
let thumbnailData=NSData(contentsOfURL:thumbnailURL)
let thumbnail=UIImage(data:thumbnailData!)
cell.imageView?.image=thumbnail
}**/
return cell
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
manager.query="http://reddit.com/r/"+searchBar.text+"/.json"
manager.data=NSMutableData()
manager.startConnection()
tableView?.reloadData()
UIApplication.sharedApplication().networkActivityIndicatorVisible == false
if UIApplication.sharedApplication().networkActivityIndicatorVisible == false{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
I didn't test it but let me know if it works for you.
try this may be this will help you.