Swift: Send data from a UITableView to UIViewController - ios

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.

Related

Not able to display values in another viewcontroller from TableView in Swift

I want to display the details of one one table row onto another viewController. But it shows an error saying ' fatal error: unexpectedly found nil while unwrapping an Optional value'
The code for my VC is as follows:
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, UITableViewDelegate,UITableViewDataSource, UICollectionViewDataSource, UICollectionViewDelegate {
#IBOutlet var nameForUser: UITextField!
#IBOutlet var loginButton: UIButton!
#IBOutlet var tableView: UITableView!
let allEvents = Events.allEvents
var nextScreenRow: Events!
override func viewDidLoad() {
super.viewDidLoad()
//nameForUser.text! = "Please Enter Name Here"
// Do any additional setup after loading the view, typically from a nib.
}
func textFieldDidBeginEditing(textField: UITextField) {
textField.text = ""
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.allEvents.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("eventsCell")!
let event = self.allEvents[indexPath.row]
cell.textLabel?.text = event.eventName
cell.imageView?.image = UIImage(named: event.imageName)
cell.detailTextLabel?.text = event.entryType
//cell.textLabel?.text = allEvents[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
nextScreenRow = allEvents[indexPath.row]
performSegueWithIdentifier("tryToConnect", sender:self)
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.allEvents.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let sec = collectionView.dequeueReusableCellWithReuseIdentifier("eventsSec", forIndexPath: indexPath) as! GridCollectionViewCell
let event = self.allEvents[indexPath.row]
sec.imageView.image = UIImage(named: event.imageName)
sec.caption.text = event.entryType
return sec
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("tryToConnect2", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "successfulLogin"){
segue.destinationViewController as! TabController
//let userName = nameForUser.text
//controller.userName = userName
}
else if (segue.identifier == "tryToConnect"){
let dest = segue.destinationViewController as! DetailedEventViewController
dest.deatiledEvent.text = nextScreenRow.eventName
dest.eventType.text = nextScreenRow.entryType
dest.imageView.image = UIImage(named: nextScreenRow.imageName)
}
}
#IBAction func loginButtonWhenPressed(sender: UIButton) {
let userName = nameForUser.text
if userName == "" {
let nextController = UIAlertController()
nextController.title = "Error!"
nextController.message = "Please enter a name"
let okAction = UIAlertAction(title: "okay", style: UIAlertActionStyle.Default) {
action in self.dismissViewControllerAnimated(true, completion: nil)
}
nextController.addAction(okAction)
self.presentViewController(nextController, animated: true, completion: nil)
}
}
}
When I run this, it shows the error. I have also assigned the delegates for the table view. The code for 'DetailedEventVC' is:
import UIKit
class DetailedEventViewController: UIViewController {
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var deatiledEvent: UILabel!
#IBOutlet weak var eventType: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// 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.
}
*/
}
Why does it show that the values are nil?
Help would be greatly appreciated.
Thanks in advance.
The 'EventsDetails.swift' file which has the details of events are a structure. Is there anything wrong in the way I'm calling the values?
import Foundation
import UIKit
struct Events {
let eventName: String
let entryType: String
let imageName: String
static let EventKey = "NameKey"
static let EntryTypeKey = "EntryType"
static let ImageNameKey = "ImageNameKey"
init(dictionary:[String : String]) {
self.eventName = dictionary[Events.EventKey]!
self.entryType = dictionary[Events.EntryTypeKey]!
self.imageName = dictionary[Events.ImageNameKey]!
}
}
extension Events {
static var allEvents: [Events] {
var eventsArray = [Events]()
for d in Events.localEventsData(){
eventsArray.append(Events(dictionary: d))
}
return eventsArray
}
static func localEventsData()-> [[String: String]] {
return [
[Events.EventKey:"Metallica Concert in Palace Grounds", Events.EntryTypeKey: "Paid Entry", Events.ImageNameKey:"Metallica"],
[Events.EventKey:"Saree Exhibition in Malleswaram Grounds", Events.EntryTypeKey: "Free Entry", Events.ImageNameKey:"SareeExhibition"],
[Events.EventKey:"Wine tasting event in Links Brewery", Events.EntryTypeKey: "Paid Entry", Events.ImageNameKey:"WineTasting"],
[Events.EventKey:"Startups Meet in Kanteerava Stadium", Events.EntryTypeKey: "Paid Entry", Events.ImageNameKey:"StartupMeet"],
[Events.EventKey:"Summer Noon Party in Kumara Park", Events.EntryTypeKey: "Paid Entry", Events.ImageNameKey:"SummerNoonParty"],
[Events.EventKey:"Rock and Roll nights in Sarjapur Road", Events.EntryTypeKey: "Paid Entry", Events.ImageNameKey:"RockNRollNight"],
[Events.EventKey:"Barbecue Fridays in Whitefield", Events.EntryTypeKey: "Paid Entry", Events.ImageNameKey:"BBQFriday"],
[Events.EventKey:"Summer workshop in Indiranagar", Events.EntryTypeKey: "Free Entry", Events.ImageNameKey:"SummerWorkshop"],
[Events.EventKey:"Impressions & Expressions in MG Road", Events.EntryTypeKey: "Free Entry", Events.ImageNameKey:"ImpressionAndExpression"],
[Events.EventKey:"Italian carnival in Electronic City", Events.EntryTypeKey: "Free Entry", Events.ImageNameKey:"ItalianCarnival"]
]
}
}
Create properties in your destination viewController and use them like below
import UIKit
class DetailedEventViewController: UIViewController {
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var deatiledEvent: UILabel!
#IBOutlet weak var eventType: UILabel!
var myImage = UIImage?
var eventDetails = ""
var typeOfEvent = ""
override func viewDidLoad() {
super.viewDidLoad()
imageView.image = myImage
deatiledEvent.text = eventDetails
eventType.text = typeOfEvent
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
and then in your first viewController you can access them like
let dest = segue.destinationViewController as! DetailedEventViewController
dest.eventDetails = nextScreenRow.eventName
dest.typeOfEvent = nextScreenRow.entryType
dest.myImage = UIImage(named: nextScreenRow.imageName)

Segue from tableview to detail doesn't work

I'm building a table view for shops in our town, and I'd like to be able to click on the name of the shop to see some more details. You can find some pictures of the main.storyboard and the files here. I also added a video of the problem with the clicking.
The code of the masterViewController is mentioned below:
import UIKit
class MasterTableViewController: UITableViewController {
// MARK: - Properties
var detailViewController: DetailViewController? = nil
var winkels = [Winkel]()
// MARK: - View Setup
override func viewDidLoad() {
super.viewDidLoad()
winkels = [
Winkel(category:"Literature", name:"Standaard"),
Winkel(category:"Literature", name:"Acco"),
Winkel(category:"Clothing", name:"H&M"),
Winkel(category:"Clothing", name:"C&A"),
Winkel(category:"Clothing", name:"Patio"),
Winkel(category:"Restaurants", name:"De 46"),
Winkel(category:"Restaurants", name:"Het hoekske"),
Winkel(category:"Supermarkets", name:"Carrefour"),
Winkel(category:"Supermarkets", name:"Colruyt")
]
winkels.sortInPlace({ $0.name < $1.name })
if let splitViewController = splitViewController {
let controllers = splitViewController.viewControllers
detailViewController = (controllers[controllers.count - 1] as! UINavigationController).topViewController as? DetailViewController
}
self.tableView.reloadData()
}
override func viewWillAppear(animated: Bool) {
clearsSelectionOnViewWillAppear = splitViewController!.collapsed
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return winkels.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let winkel = winkels[indexPath.row]
cell.textLabel!.text = winkel.name
cell.detailTextLabel?.text = winkel.category
return cell
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = tableView.indexPathForSelectedRow {
let winkel = winkels[indexPath.row]
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
controller.detailWinkel = winkel
controller.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
}
The last part shows the segue to the next navigation controller (named showDetail, and is of kind "show Detail (e.g. replace)".
Below is the code of the detailViewController:
import UIKit
class DetailViewController: UIViewController {
#IBOutlet weak var detailDescriptionLabel: UILabel!
#IBOutlet weak var WinkelImageView: UIImageView!
var detailWinkel: Winkel? {
didSet {
configureView()
}
}
func configureView() {
if let detailWinkel = detailWinkel {
if let detailDescriptionLabel = detailDescriptionLabel, WinkelImageView = WinkelImageView {
detailDescriptionLabel.text = detailWinkel.name
WinkelImageView.image = UIImage(named: detailWinkel.name)
title = detailWinkel.category
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
configureView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I'm not sure what i'm doing wrong so that the clicking won't work.. Thanks in advance for teaching me how to fix this!
You need to implement the method didSelectRowAtIndexPath for the tableview in the first class. In this, you will perform the segue that actually moves from one ViewController to another.

Array does not stacking Class object

I am trying to initialize and then append Class object to array through delegate func. Delegate Double comes from button press with some data.
var expensesArray = [SpendedMoneyObject]()
var delegatedDouble:Double = 0.0
func setExpenses(expensesFromMainView: Double) {
delegatedDouble = expensesFromMainView
var aSpendedMoneyObject = SpendedMoneyObject(moneySpent: delegatedDouble)
expensesArray += [aSpendedMoneyObject]
self.tableView.reloadData()
}
Problem here is that I am trying to show array at TableViewCell, but it doesn't showing at all, I guess main problem is that expensesArray value is 1 and it's not stacking but replacing same array with other value. Will be really happy to hear what you think.
Edit:
I tried .append and it still the same also TableView func cellForRowAtIndexPath does not getting called.
class ExpensesTableViewController: UITableViewController, ExpensesEnteredDelegate{
//MARK : Properties
var expensesArray = [SpendedMoneyObject]()
var delegatedDouble:Double = 0.0
override func viewDidLoad() {
super.viewDidLoad()
}
func setExpenses(expensesFromMainView: Double) {
delegatedDouble = expensesFromMainView
var aSpendedMoneyObject = SpendedMoneyObject(moneySpent: delegatedDouble)
expensesArray.append(aSpendedMoneyObject)
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return expensesArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "ExpensesCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! ExpensesTableViewCell
print("Iam here")
let expense = expensesArray[indexPath.row]
let fromDoubleToString = "\(expense.moneySpent)"
cell.loadItemsToCell(fromDoubleToString, date: expense.date)
return cell
}
Object class:
class SpendedMoneyObject {
var moneySpent: Double
var currentTime = NSDate().toShortTimeString()
var date: String
init(moneySpent: Double) {
self.date = currentTime
self.moneySpent = moneySpent
}}
Edit: I can now add more than one array by moving new ViewController creation from spendButton func which was creating newVC every time i clicked button. Here are edited code:
protocol ExpensesEnteredDelegate {
func setExpenses(expensesFromMainView: Double)
}
class MainViewController: UIViewController {
#IBOutlet weak var moneyTextField: UITextField!
var delegate: ExpensesEnteredDelegate? = nil
override func viewDidLoad() {
super.viewDidLoad()
// Defining ExpensesVC
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let newExpensesVC = storyboard.instantiateViewControllerWithIdentifier("ExpensesTableView") as! ExpensesTableViewController
delegate = newExpensesVC
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func spentButton(sender: AnyObject) {
// Delegating expenses Double value
if (delegate != nil) {
let myDouble = Double(moneyTextField.text!)
let expenses: Double = myDouble!
delegate!.setExpenses(expenses)
}
}}
But still array's data does not showing up in a tableView
Try this code example:
let aSpendedMoneyObject = SpendedMoneyObject(moneySpent: delegatedDouble)
expensesArray.append(aSpendedMoneyObject)
Or you can use .extend() method if you are looking to append more elements from a different array to your array.
instead of
expensesArray += [aSpendedMoneyObject]
try
expensesArray.append(aSpendedMoneyObject)

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?

Data being passed from UITableView to new Controller, SWIFT

I've been at this for a while and I can not figure out how to pass data from the table view cell to a new "detail" controller. I understand the segue that connects it to a new controller but setting variables in that class to some values fails (doesn't show the values). This is what I currently have:
import UIKit
class BuyTreeViewController: UITableViewController, UISearchBarDelegate, UISearchDisplayDelegate {
var products : [Product] = []
var filteredProducts = [Product]()
override func viewDidLoad() {
self.products = [
Product(name:"Chocolate", price: 11, description: "i"),
Product(name:"Candy", price: 12, description: "h"),
Product(name:"Break", price: 13, description: "g"),
Product(name:"Apple", price: 14, description: "f"),
Product(name:"Computer", price: 15, description: "e"),
Product(name:"Laptop", price: 16, description: "d"),
Product(name:"Cup", price: 17, description: "c"),
Product(name:"Table", price: 18, description: "b"),
Product(name:"Chair", price: 19, description: "a")
]
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.searchDisplayController!.searchResultsTableView {
return self.filteredProducts.count
} else {
return self.products.count
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//ask for a reusable cell from the tableview, the tableview will create a new one if it doesn't have any
let cell = self.tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell
var product : Product
// Check to see whether the normal table or search results table is being displayed and set the Candy object from the appropriate array
if tableView == self.searchDisplayController!.searchResultsTableView {
product = filteredProducts[indexPath.row]
} else {
product = products[indexPath.row]
}
// Configure the cell
cell.textLabel!.text = product.name
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
return cell
}
func filterContentForSearchText(searchText: String, scope: String = "All") {
self.filteredProducts = self.products.filter(
{
( product : Product) -> Bool in
var categoryMatch = (scope == "All") || (product.category == scope)
var stringMatch = product.name.rangeOfString(searchText)
return categoryMatch && (stringMatch != nil)
})
}
func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchString searchString: String!) -> Bool {
let scopes = self.searchDisplayController!.searchBar.scopeButtonTitles as [String]
let selectedScope = scopes[self.searchDisplayController!.searchBar.selectedScopeButtonIndex] as String
self.filterContentForSearchText(searchString, scope: selectedScope)
return true
}
func searchDisplayController(controller: UISearchDisplayController!,
shouldReloadTableForSearchScope searchOption: Int) -> Bool {
let scope = self.searchDisplayController!.searchBar.scopeButtonTitles as [String]
self.filterContentForSearchText(self.searchDisplayController!.searchBar.text, scope: scope[searchOption])
return true
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier("productDetail", sender: tableView)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if segue.identifier == "productDetail" {
// let productDetailViewController = segue.destinationViewController as UIViewController
let productDetailViewController = segue.destinationViewController as ProductDetailViewController
productDetailViewController.testLabel.text = "123345"
if sender as UITableView == self.searchDisplayController!.searchResultsTableView {
let indexPath = self.searchDisplayController!.searchResultsTableView.indexPathForSelectedRow()!
let destinationTitle = self.filteredProducts[indexPath.row].name
productDetailViewController.title = destinationTitle
} else {
let indexPath = self.tableView.indexPathForSelectedRow()!
let destinationTitle = self.products[indexPath.row].name
productDetailViewController.title = destinationTitle
}
productDetailViewController.productPriceText = "10"
productDetailViewController.productTitleText = "100"
productDetailViewController.productDescriptionText = "100"
}
}
And this is what I have in the ProductDetailViewController:
import UIKit
class ProductDetailViewController: UIViewController {
#IBOutlet weak var productDescription: UITextView!
#IBOutlet weak var productPrice: UITextField!
#IBOutlet weak var productTitle: UITextField!
#IBOutlet weak var connectUserButton: UIButton!
#IBOutlet weak var testLabel: UILabel!
// var productDescriptionText: String
// var productPriceText: String
// var productTitleText: String
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// productDescription.text = productDescriptionText
// productPrice.text = productPriceText
// productTitle.text = productTitleText
}
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.
}
*/
#IBAction func contactUserClicked(sender: AnyObject) {
println("conentUserButton clicked")
}
For your prepareForSegue:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if segue.identifier == "productDetail" {
let indexPath = self.tableView.indexPathForSelectedRow()
let theSelectedRow = filteredProducts[indexPath!.row]
let theDestination = segue.destinationViewController as ProductDetailViewController
theDestination.productPriceText = "10"
theDestination.productTitleText = "100"
theDestination.productDescriptionText = "100"
} else
//only needed if more than one segue
}
}
Your detailViewController looked good to me. If you still have issues, I will post a more complete example.

Resources