Label to display item in array in not visible - ios

Right now im following a tutorial. And i notice when i click a table cell and redirect to a new view, i found there is no detail for each cell.
ViewController.swift:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var itemsArray: [ToDoItem] = []
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemsArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell!
let tempItem = itemsArray[indexPath.row]
cell.textLabel?.text = tempItem.itemName
return cell!
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "detailsegue" {
let destVC = segue.destinationViewController as! DetailViewController
let selectedIndex = tableView.indexPathForSelectedRow
destVC.myItem = itemsArray[selectedIndex!.row] as? ToDoItem
}
}
override func viewDidLoad() {
super.viewDidLoad()
let item1 = ToDoItem(name: "Eat", desc: "Eat until i am full. I prefer local food though!", place: "Food Court")
itemsArray.append(item1)
let item2 = ToDoItem(name: "Drink", desc: "Drink until i am full. I prefer local drink though!", place: "Drink Court")
itemsArray.append(item2)
let item3 = ToDoItem(name: "Jump", desc: "Jump until i am tired. I prefer local jump though!", place: "Sport Center")
itemsArray.append(item3)
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
ToDoItem.swift:
import UIKit
class ToDoItem: NSObject {
var itemName: String
var itemDescription: String?
var itemPlace : String?
var completed: Bool
init(name: String, desc: String?, place:String?) {
self.itemName = name
self.itemDescription = desc
self.itemPlace = place
self.completed = false
}
}
my detailviewcontroller.swift
import UIKit
class DetailViewController: UIViewController {
var myItem: ToDoItem?
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var placeLabel: UILabel!
#IBOutlet weak var descLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
nameLabel.text = myItem?.itemName
placeLabel.text = myItem?.itemDescription
// Do any additional setup after loading the view.
}
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.
}
*/
}
and here is my storyboard:
storyboard

Related

Segueing to a different tab in a UITabController

I am trying to segue data from my "create a party" form into my second "Find Parties" tab.
Here is a screen shot of my main story board:
my code for the create a party controller:
import UIKit
struct party {
var name: String
var location: String
var description: String
}
class FirstViewController: UIViewController {
#IBOutlet weak var nameField: UITextField!
#IBOutlet weak var locationField: UITextField!
#IBOutlet weak var descriptionField: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var newParty = party(name: "", location: "", description: "")
#IBAction func create(_ sender: AnyObject) {
newParty = party(name: nameField.text!, location: locationField.text!, description: descriptionField.text!)
nameField.text = ""
locationField.text = ""
descriptionField.text = ""
performSegue(withIdentifier: "toPartyList", sender: newParty)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationViewController : SecondViewController = segue.destination as! SecondViewController
destinationViewController.parties.append(newParty)
}
}
Code for the find parties tab:
import UIKit
class SecondViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var partyTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
partyTable.delegate = self
partyTable.dataSource = self
// updates the table of users everytime submit is clicked
DispatchQueue.main.async{
self.partyTable.reloadData()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var parties = [party]()
// creates the number of cells in the table
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return parties.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Make table cells the show the user name
let cell = UITableViewCell()
cell.textLabel?.text = parties[indexPath.row].name
return cell
}
// Allows the user to swipe and delete people from the table and also the users array
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// delete the person in users array
parties.remove(at: indexPath.row)
// delete the cell from the table
partyTable.deleteRows(at: [indexPath], with: .fade)
}
}
}
currently my segue just takes me directly to the "Find Parties" view controller with no way back, and not to the tab. what do I need to change in my segue to do this?
Rather than use a segue in this case, just switch tabs programatically:
#IBAction func create(_ sender: AnyObject) {
newParty = party(name: nameField.text!, location: locationField.text!, description: descriptionField.text!)
nameField.text = ""
locationField.text = ""
descriptionField.text = ""
tabBarController?.selectedIndex = 1 // 2nd tab
}
To pass information along, you can do something like this:
let navVC = tabBarController.viewControllers[1] as! UINavigationController
let rootVC = navVC.viewControllers[0] as! SomeViewController
rootVC.someData = myData

Swift passing array between swift files for tableview

I have a button action in one viewcontroller connect to another tableviewcontroller. I need to pass a few textfields value to show in another tableview via click the button. In the first view, I have a global array:
var estRent = [AnyObject]()
Append value within the buttonAction:
#IBAction func calculateButtonAction(sender: UIButton) {
...
estRent.append(weekRent)
estRent.append(monthRent)
estRent.append(yearRent)
estRent.append(interestRate)
estRent.append(loanAmount)
estRent.append(monthInterest)
}
Overwrite prepareForSegue:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "Load View") {
let svc = segue.destinationViewController as! NextTableViewController
svc.rentArray = self.estRent
}
}
In the NextTableViewController, there is a global array:
var rentArray = [AnyObject]()
The next table view could not see the values in the array. Appreciate any help.
First View Controller:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var ageTextField: UITextField!
#IBOutlet weak var classTextField: UITextField!
var estRent = [AnyObject]()
#IBAction func goButtonAction(sender: UIButton) {
estRent.append(nameTextField.text!)
estRent.append(ageTextField.text!)
estRent.append(classTextField.text!)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
[estRent .removeAll()]
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
print(estRent)
if (segue.identifier == "LoadView") {
let svc = segue.destinationViewController as! RentTableViewController
svc.rentArray = self.estRent
}
}
}
RentTableViewController:
import UIKit
class RentTableViewController: UITableViewController {
var rentArray = [AnyObject]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return rentArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "studentCell")
let tableCell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("studentCell", forIndexPath: indexPath)
let rentLabel: UILabel = UILabel.init(frame: CGRectMake(10, 10, 100, 25))
rentLabel.text = rentArray[indexPath.row] as? String
tableCell.addSubview(rentLabel)
return tableCell
}
}
Click here for Main.storyboard image
You must give a segue identifier as "LoadView" in storyboard
Click here to view screen short for "How to give segue identifier"

Swift tableview in popover doesn't show data

I am trying to setup a popover view containing a textfield and a tableview, but I couldn't make the tableview to show the data. It would be much appreciated if you could help me on this.
On the main ViewController, I put a label to trigger the segue of popover,
import UIKit
class ViewController: UIViewController, UIPopoverPresentationControllerDelegate {
#IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func popover(sender: AnyObject) {
self.performSegueWithIdentifier("ShowDetails", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowDetails" {
if let controller = segue.destinationViewController as? UIViewController {
controller.popoverPresentationController!.delegate = self
controller.preferredContentSize = CGSize(width: 320, height: 50)
}
}
}
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return .None
}
}
A PopoverCell is setup for the prototype cell,
import UIKit
class PopoverCellTableViewCell: UITableViewCell {
#IBOutlet weak var AreaCellLabel: 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
}
}
A PopoverControllerView is set for the popover itself.
import UIKit
class PopoverViewController: UIViewController, UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate {
var areas = [Area]()
// #IBOutlet weak var NewArea: UITextField!
// #IBOutlet weak var SaveNewArea: UIButton!
#IBOutlet weak var subtableView: UITableView!
override func viewDidLoad() {
subtableView.dataSource = self
subtableView.delegate = self
super.viewDidLoad()
LoadsampleArea()
// Do any additional setup after loading the view.
}
func LoadsampleArea () {
let area1 = Area(AreaName:"Moountain")!
let area2 = Area(AreaName:"ByHill")!
let area3 = Area(AreaName:"Yard")!
areas += [area1, area2, area3]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return areas.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Table view cells are reused and should be dequeued using a cell identifier.
let cellIdentifier = "AreaCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! PopoverCellTableViewCell
let area = areas[indexPath.row]
cell.AreaCellLabel.text = area.AreaName
dismissViewControllerAnimated(true, completion:nil)
return cell
}
}
and a simple data file to put the data.
import UIKit
class Area {
var AreaName: String
init? (AreaName: String) {
self.AreaName = AreaName
if AreaName.isEmpty {
return nil
}
}
}
Where is your UITableView object in your PopoverViewController class ? I can't see any reference to it.
Maybe your didn't copy-paste it since the textfield is commented too, in this case I'll suggest to check if the delegate an datasource are set property.

Swift: Send data from a UITableView to UIViewController

I have a list of Cities in a TableView and want to pass the data from the cell in TableView to a UIViewController. Now when I pass the data I also want to pass the Latitude and Longitude of those Cities to the UIViewController. Here is the TableViewController code.
class MasterTableViewController: UITableViewController
{
let fruits = ["London", "Melbourne", "Singapore", "Brazil", "Germany", "Monza", "Dallas", "Auckland", "Brussels", "Shanghai", "Sepang", "Barcelona"]
override func awakeFromNib() {
super.awakeFromNib()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow() {
let fruit = fruits[indexPath.row]
(segue.destinationViewController as! ViewController).detailItem = fruit
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fruits.count
}
override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
if (indexPath.row == 0){
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
let fruit = fruits[indexPath.row]
cell.textLabel!.text = fruit
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
}
I can pass City but how would you pass the latitude of the longitude of the cities to the UIViewController. Here is the code for the UIViewController.
class ViewController: UIViewController {
#IBOutlet weak var currentTemperatureLabel: UILabel?
#IBOutlet weak var currentHumidityLabel: UILabel?
#IBOutlet weak var currentPrecipitationLabel: UILabel?
#IBOutlet weak var currentWeatherIcon: UIImageView?
#IBOutlet weak var currentWeatherSummary: UILabel?
#IBOutlet weak var refreshButton: UIButton?
#IBOutlet weak var activityIndicator: UIActivityIndicatorView?
#IBOutlet weak var detailDescriptionLabel: UILabel?
// Location coordinates
let coordinate: (lat: Double, lon: Double) = (37.8267,-122.423)
// TODO: Enter your API key here
private let forecastAPIKey = ""
var detailItem: AnyObject? {
didSet {
// Update the view.
self.configureView()
}
}
func configureView() {
if let detail: AnyObject = self.detailItem {
if let label = self.detailDescriptionLabel {
label.text = detail.description
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.configureView()
retrieveWeatherForecast()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func retrieveWeatherForecast() {
let forecastService = ForecastService(APIKey: forecastAPIKey)
forecastService.getForecast(coordinate.lat, lon: coordinate.lon) {
(let currently) in
if let currentWeather = currently {
dispatch_async(dispatch_get_main_queue()) {
if let temperature = currentWeather.temperature {
self.currentTemperatureLabel?.text = "\(temperature)ยบ"
}
if let humidity = currentWeather.humidity {
self.currentHumidityLabel?.text = "\(humidity)%"
}
if let precipitation = currentWeather.precipProbability {
self.currentPrecipitationLabel?.text = "\(precipitation)%"
}
if let icon = currentWeather.icon {
self.currentWeatherIcon?.image = icon
}
if let summary = currentWeather.summary {
self.currentWeatherSummary?.text = summary
}
self.toggleRefreshAnimation(false)
}
}
}
}
#IBAction func refreshWeather() {
toggleRefreshAnimation(true)
retrieveWeatherForecast()
}
func toggleRefreshAnimation(on: Bool) {
refreshButton?.hidden = on
if on {
activityIndicator?.startAnimating()
} else {
activityIndicator?.stopAnimating()
}
}
}
Add a property for the location to ViewController.
You can then pass the city's location in MasterTableViewController prepareForSegue, similar to how you're passing the city (detailItem) now.
Update:
To pass another parameter, you would add it to your ViewController
var coordinateItem: AnyObject? {
didSet {
// Update the view.
self.configureView()
}
}
and then pass it in prepareForSegue
(segue.destinationViewController as! ViewController).coordinateItem = location
Update 2:
Yes, you can initialize an array of coordinates, and pass a latitude and longitude coordinate.
var locations : [[Double]] = [[51.50722, -0.12750], [-37.8136, 144.9631], ...]
In this case, your coordinateItem would be a [Double].
You can access the two doubles by coordinateItem[0] and coordinateItem[1]
The general concept is the same, regardless of whether you're passing an array or a String.

Trying to pass array of coordinates to a UIViewController

I am trying to pass coordinates to a UIViewController. How would I would be able to accessing them. Here is the code for the TableViewController
class MasterTableViewController: UITableViewController
{
let fruits = ["London", "Melbourne", "Singapore", "Brazil", "Germany"]
let locations: [[Double]] = [[51.50722, -0.12750],[-37.8136, 144.9631],[-23.5475000,-46.6361100],[49.3297,8.57428],[45.58005,9.27246]]
override func awakeFromNib() {
super.awakeFromNib()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow() {
let fruit = fruits[indexPath.row]
let location = locations[indexPath.row]
(segue.destinationViewController as! ViewController).detailItem = fruit
(segue.destinationViewController as! ViewController).coordinateItem = location
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fruits.count
}
override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
if (indexPath.row == 0){
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
let fruit = fruits[indexPath.row]
cell.textLabel!.text = fruit
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
}
This is the code for the UIViewController.
class ViewController: UIViewController {
#IBOutlet weak var currentTemperatureLabel: UILabel?
#IBOutlet weak var currentHumidityLabel: UILabel?
#IBOutlet weak var currentPrecipitationLabel: UILabel?
#IBOutlet weak var currentWeatherIcon: UIImageView?
#IBOutlet weak var currentWeatherSummary: UILabel?
#IBOutlet weak var refreshButton: UIButton?
#IBOutlet weak var activityIndicator: UIActivityIndicatorView?
#IBOutlet weak var detailDescriptionLabel: UILabel?
// Location coordinates
var coordinate: (lat: Double, lon: Double) = (37.8267,-122.423)
// TODO: Enter your API key here
private let forecastAPIKey = ""
var coordinateItem: AnyObject? {
didSet {
// Update the view.
self.configureView()
}
}
var detailItem: AnyObject? {
didSet {
// Update the view.
self.configureView()
}
}
func configureView() {
if let detail: AnyObject = self.detailItem {
if let label = self.detailDescriptionLabel {
label.text = detail.description
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.configureView()
retrieveWeatherForecast()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func retrieveWeatherForecast() {
let forecastService = ForecastService(APIKey: forecastAPIKey)
forecastService.getForecast(coordinate.lat, lon: coordinate.lon) {
(let currently) in
if let currentWeather = currently {
dispatch_async(dispatch_get_main_queue()) {
How would I be able to have the weather of the selected country updated. I understand that I need to get access to the coordinates in the TableViewController. So how can I do this in the function Retrieve Weatherforecast?

Resources