Swift tableview in popover doesn't show data - ios

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.

Related

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"

Using UITableView in detail, how to display string in TextView (Master-Detail project, Swift, iOS)

I want to use a TableView for the detail side of a Master Detail app. I have started with the standard Master Detail project in Xcode, deleted the standard app that comes with it, deleted the standard UIView detail controller, added a TableView controller, added a TextView to the prototype cell for testing, and created a new segue to the new TableView. I subclassed UITableViewCell and created an outlet (detailTextView) from the TextView to the subclass (TableViewCell). Changed the class in DetailViewController.swift from UIViewController to UITableViewController. I am successfully passing a string stringForTextView = "String for TextView" from master to the detail. But I can't figure out how to display that string in the TextView. I tried to reference the TextView text in the detail view through the outlet (detailTextView.text) but got "Use of unresolved identifier detailTextView"
Any help will be greatly appreciated.
Relevant code is shown below.
You can also download the whole project here if that would be helpful:
http://greendept.com/MasterDetailTwoTableViews/
TableViewCell.swift (subclass for prototype cell in detail)
import UIKit
class TableViewCell: UITableViewCell {
#IBOutlet weak var detailTextView: UITextView!
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
}
}
DetailViewController.swift
import UIKit
class DetailViewController: UITableViewController {
var stringForTextView : String?
var detailItem: AnyObject? {
didSet {
// Update the view.
self.configureView()
}
}
func configureView() {
// THE NEXT TWO LINES WORK: PASSED IN STRING PRINTS TO CONSOLE
let printThis = stringForTextView! as String
print("\(printThis)")
// BUT THE REFERENCE TO THE OUTLET BELOW DOES NOT WORK, GIVES
// "Use of unresolved identifier detailTextView"
detailTextView.text = printThis
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.configureView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
MasterViewController.swift
import UIKit
class MasterViewController: UITableViewController {
var detailViewController: DetailViewController? = nil
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
}
override func viewWillAppear(animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed
super.viewWillAppear(animated)
}
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 controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
controller.stringForTextView = "String for TextView"
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
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
}
}
DetailViewController is a UITableViewController, and you can't access the detailTextView in the tableView controller. You defined the outlet in the cell, and that is where you can access and configure the detailTextView.
It doesn't make any sense to have the DetailViewController as a UITableViewController, if what you really want is to configure the text view there. Then you should set it back to a UIViewController, and add the text view as a single UITextView to the view controllers view.
This link below shows how you can change text in a cell label even though the outlet to the textview is in the cell subclass. It shows this with a single TableView.
creating custom tableview cells in swift
In adapting the above approach for my test project, I didn't have to change the Master at all. In the Detail view, the configureView() doesn't do the main job of updating the TextView. That happens in cellForRowAtIndexPath -- second to the last function in detail view. Another difference is I could not, and did not need to, implement #IBOutlet var tableView: UITableView! -- because tableView was already available as a stored property. I also had to add overrride in a couple of places. Finally, in the TableViewCell class, I added an outlet linked to the content view of the TextView. The result is that the TextView text is getting updated.
TableViewCell.swift:
import UIKit
class TableViewCell: UITableViewCell {
#IBOutlet weak var detailTextView: UITextView!
#IBOutlet weak var detailContentView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
print ("awakeFromNib")
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
print("test")
}
}
DetailViewController.swift:
import UIKit
class DetailViewController: UITableViewController {
// #IBOutlet var tableView: UITableView! -- cannot override a stored property
var stringForTextView : String?
// Don't forget to enter this in IB also
let cellReuseIdentifier = "reuseIdentifier"
var detailItem: AnyObject? {
didSet {
// Update the view.
self.configureView()
}
}
func configureView() {
// Update the user interface for the detail item.
// stringForTextView
let printThis = stringForTextView! as String
print("\(printThis)")
// detailTextView.text = printThis
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
self.configureView()
}
// needed "override" here
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
// create a cell for each table view row
// needed "override" here
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:TableViewCell = self.tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) as! TableViewCell
cell.detailTextView.text = stringForTextView
print("cell.detailTextView.text: \(cell.detailTextView.text)")
print("row : \(indexPath.row)")
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

Why is my tableViewController not loading any data?

Im creating an app where different buttons in a ViewController load different menu's into the tableViewController. The buttons are linked by a prepare for segue and the menu's (arrays) are linked by a contentMode. 1: breakfast menu & 2: lunch menu. I had allot of help from someone setting this up but now the table is not loading any data... The cell has 3 labels which display an item, info and price. It changes value within the code when a contentMode is selected. Does anyone see the problem in my code? thanks a lot!
import UIKit
class foodMenuController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let foodMenuController = segue.destinationViewController as! foodTableViewController
if segue.identifier == "showBreakfast" {
foodMenuController.contentMode = 1
} else if segue.identifier == "showLunch" {
foodMenuController.contentMode = 2
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
import UIKit
class foodTableViewCell: UITableViewCell {
#IBOutlet weak var foodItem: UILabel!
#IBOutlet weak var foodDescription: UILabel!
#IBOutlet weak var foodPrice: 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
}
}
import UIKit
class foodTableViewController: UITableViewController {
//Content Mode Selection in menu
var contentMode = 0
// THIS SHOULD BE LOADED WHEN CONTENT MODE is "1" --> BREAKFAST
let breakfastItems = ["Bread", "Coffee", "Nada"]
let breakfastInfo = ["Good", "Nice", "Nothing"]
let breakfastPrice = ["$1", "$100", "$12,40"]
// THIS SHOULD BE LOADED WHEN CONTENT MODE IS "2" --> LUNCH
let lunchItems = ["Not bread", "Not Coffee", "Something"]
let lunchInfo = ["Not good", "Not nice", "Yes"]
let lunchPrice = ["$1", "$100", "$12,40"]
var foodItems: [String] = []
var foodInfo: [String] = []
var foodPrice: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
switch (contentMode){
case 1: contentMode = 1
foodItems = breakfastItems
foodInfo = breakfastInfo
foodPrice = breakfastPrice
case 2: contentMode = 2
foodItems = lunchItems
foodInfo = lunchInfo
foodPrice = lunchPrice
default:
break
}
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section:
Int) -> Int {
return foodItems.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "Cell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! foodTableViewCell
cell.foodItem.text = foodItems[indexPath.row]
cell.foodDescription.text = foodInfo[indexPath.row]
cell.foodPrice.text = foodPrice[indexPath.row]
return cell
}
}
There isn't anything apparently wrong with the snippet you shared. You can check what is returned in the tableView:numberOfRowsInSection: method and see if it is returning a value > 0
Also, this is a given but we've all done it at some point of time - check to make sure the tableview delegate and datasource are set to your viewcontroller.
I have made slight modifications in your project.
1. make the UINavigationController the InitialViewController
2. make the FoodMenuController the root of UINavigationController
Now modify your FoodMenuController
#IBOutlet weak var bakeryButton: UIButton!
#IBOutlet weak var breakfastButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBarHidden = true //hide navigationBar in first ViewController
self.bakeryButton.addTarget(self, action: "bakeryButtonAction:", forControlEvents: .TouchUpInside)
self.breakfastButton.addTarget(self, action: "breakfastButtonAction:", forControlEvents: .TouchUpInside)
}
func bakeryButtonAction(sender: UIButton) {
performSegueWithIdentifier("showLunch", sender: self)
}
func breakfastButtonAction(sender: UIButton) {
performSegueWithIdentifier("showBreakfast", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let foodTableViewController: FoodTableViewController = segue.destinationViewController as! FoodTableViewController
if segue.identifier == "showBreakfast" {
foodTableViewController.contentMode = 1
} else if segue.identifier == "showLunch" {
foodTableViewController.contentMode = 2
}
}
Also you can make UINavigationBar visible in FoodTableViewController
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBarHidden = false
}
PS: It is always better not to add segue directly to a UIButton. Alternatively you can add it from the yellow button on top of your FoodMenuController and specify the segue to be fired in UIButtonAction using performSegueWithIdentifier
I can no where see you setting the datasource and delegate of the tableView, please cross check these are both setup.

Swift 2 Nil Delegate

So I want to create a IOS application that generates a group of students, adds them to a course and then shows students. I can show students in a list in a table view but now I want to let the user touch a student's name and be taken to a page with information about that student (name highest grade etc). The student class is flawless, the course works and the only problem I have is that I can't get a student from one view to the other.
Here's what I have so far:
//
// DataTableViewController.swift
// assignment8
//
import Foundation
import UIKit
class DataTableViewController: UITableViewController {
var delegate:StudentSelectionDelegate! = nil
var students = [Student]();
var course = Course();
// MARK: - UITableViewDataSource
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
func didSelectStudent(controller:UITableViewController, student:Student!) {
controller.navigationController?.popViewControllerAnimated(true)
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
self.course = courseStorage.getCourse();
self.students = course.getArrayOfStudentSortedByLastName();
return course.count;
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let row = indexPath.row
let currentStudent = students[row];
if (delegate != nil) {
delegate.didSelectStudent(self,student:currentStudent)
}
else {
print ("delegate is nil :(");
}
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("studentCell", forIndexPath: indexPath)
cell.textLabel?.text = students[indexPath.row].lastName + ", " +
students[indexPath.row].firstName;
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
print("ping");
if segue.identifier == "studentSegue" {
let nextScene = segue.destinationViewController as! studentViewController
// Pass the selected object to the new view controller.
if let indexPath = self.tableView.indexPathForSelectedRow {
let selectedStudent = students[indexPath.row]
print (selectedStudent.firstName);
nextScene.student = selectedStudent;
}
}
}
}
and
//
// DataViewController.swift
// assignment8
//
import UIKit
class DataViewController: UIViewController {
#IBOutlet weak var dataLabel: UILabel!
var dataObject: String = ""
let tableData = ["One","Two","Three"];
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 viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.dataLabel!.text = dataObject
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int)
-> Int {
return self.tableData.count;
}
}
and
//
// studentViewController.swift
// assignment8
//
import UIKit
protocol StudentSelectionDelegate {
func didSelectStudent(controller: UITableViewController, student:Student)
}
class studentViewController: UIViewController {
var delegate = StudentSelectionDelegate.self;
var name = String();
var student = Student();
#IBOutlet weak var StudentName: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func didSelectStudent(controller:UITableViewController, student:Student!) {
student.description;
print ("pong")
StudentName.text = student.firstName + " " + student.lastName;
controller.navigationController?.popViewControllerAnimated(true);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// override func viewWillAppear(animated: Bool) {
// StudentName.text = name
// }
}
This is my storyboard so far.
So, any time I try clicking a student it will print the message that I've decided to use if the delegate is nil. So far I've tried looking at all the other answers on SO but none of them have fixed my issue.
To be able to send information from one view controller to another you should use segues. It seems like that's what you're doing according to the image. If you don't know how to use a segue, you can find a good answer here: Sending data with Segue with Swift
With segues you'll be able to set the delegate of the next view controller:
protocol MyDelegate {
func myFunction()
}
class FirstViewController: UIViewController, MyDelegate {
func myFunction() {
// do what the function does
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let secondVC = segue.destinationViewController as? SecondViewController {
secondVC.delegate = self
}
}
}
class SecondViewController: UIViewController {
var delegate: MyDelegate!
}
Before you segue to the second view controller (you're preparing for the segue), you set the delegate variable of SecondViewController to self, because FirstViewController conforms to MyDelegate protocol so it can be used there. Now, in SecondViewController you can use delegate.myFunction() and it will do whatever is written inside the FirstVC's function, because the FirstVC is SecondVC's delegate.

Passing data from one tableview to another tableview using segue in swift

I am really struggling to pass data from SecondViewController to ActivityFormTableViewController.
get this error: 'NSInvalidArgumentException', reason: 'Receiver () has no segue with identifier 'MajorActivity''
Code for two classes follow:
Any help would be received with gratitude.
//
// SecondViewController.swift
// LinkByActivity
//
// Created by Jeremy Andrews on 2015/06/10.
// version update 23/06/2015
// Copyright (c) 2015 Jeremy Andrews. All rights reserved.
//
import UIKit
class SecondViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet var tableView: UITableView!
let textCellIdentifier = "TextCell"
var catRet = XnYCategories.mainCats("main")
var activityDictionary = [String : [String]]()
var key1:String!
#IBAction func ActivityMainCats(segue:UIStoryboardSegue) {
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
// MARK: UITextFieldDelegate Methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return catRet.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) as! UITableViewCell
let row = indexPath.row
cell.textLabel?.text = catRet[row]
return cell
}
// MARK: UITableViewDelegate Methods
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
var row = indexPath.row
let key1 = catRet[row]
println(key1)
performSegueWithIdentifier("MajorActivity", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "MajorActivity") {
var svc = segue.destinationViewController as! ActivityFormTableViewController;
svc.key2 = key1
println(key1)
}
}
}
//
// ActivityFormTableViewController.swift
// LinkByActivity
//
// Created by Jeremy Andrews on 2015/07/24.
// Copyright (c) 2015 Jeremy Andrews. All rights reserved.
//
import UIKit
class ActivityFormTableViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet var tableView2: UITableView!
var key2:String!
var catRet2 = XnYCategories.mainCats("Sport")
let textCellIdentifier = "TextCell2"
var activityDictionary = [String : [String]]()
override func viewDidLoad() {
super.viewDidLoad()
println(key2)
var catRet2 = XnYCategories.mainCats(key2)
println(catRet2)
tableView.delegate = self
tableView.dataSource = self
}
// MARK: UITextFieldDelegate Methods
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//var catRet2 = XnYCategories.mainCats(key2)
return catRet2.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) as! UITableViewCell
let row = indexPath.row
cell.textLabel?.text = catRet2[row]
return cell
}
// MARK: UITableViewDelegate Methods
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
var row = indexPath.row
let activityKey = "CellNo_" + "famNam_" + key2
activityDictionary = [activityKey: ["TheForm", "l1", "etc"]]
//println(activityDictionary)
}
}
You need to create a UINavigationController in your prepareForSegue method because it appears as that's what you have on your storyboard. Then you need to create an instance of the controller that you want the navigation controller to show and assign your properties to that.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "MajorActivity") {
let activityFormNavController = segue.destinationViewController as! UINavigationController
let svc = activityFormNavController.topViewController as! ActivityFormTableViewController
svc.key2 = key1
println(key1)
}
}
Storyboard Example:
ViewController.swift
import UIKit
class ViewController: UIViewController {
var someString : String?
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 fireSegueBttnTouched(sender: AnyObject) {
// set my local instance variable to some value to pass
someString = "Stack Overflow Is Great!"
performSegueWithIdentifier("next", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "next" {
// Create a UINavigationController instance first b/c that's where the segue goes
let nextNavVc = segue.destinationViewController as! UINavigationController
// Create an instance of the top view controller belonging to the above crated navigation controller
let nextVc = nextNavVc.topViewController as! SecondViewController
// Assign the instance variable from this view controller to the variable on the view controller nextVc
nextVc.passedString = someString
}
}
}
SecondViewController.swift
import UIKit
class SecondViewController: UIViewController {
#IBOutlet weak var outputLabel: UILabel!
var passedString : String?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidLayoutSubviews() {
if passedString != nil {
outputLabel.text = passedString!
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Simulator Screenshots:

Resources