How to bring UIImageView to foreground upon tapping a tableViewCell? - ios

currently thumbnails are being shown in UITableViewCell and upon tapping a cell, I want the image to be shown in foreground with a cross/X button on right top to dismiss the image and show tableView. I have the following code in didSelectRow:
let hoverImage = UIImageView()
hoverImage.image = UIImage(named: "splashpt")
hoverImage.contentMode = .scaleAspectFit
self.view.addSubview(hoverImage)
hoverImage.center = self.view.center
hoverImage.layer.zPosition = 5
self.view.bringSubview(toFront: hoverImage)
Still the image doesn't show up. The computation is hitting this section of the code because I'm able to debug and step through this part of the code. But nothing shows up on screen. I'm using the zPosition AND bringSubview(toFront:) and neither of the seem to work for my requirement. Any help would be greatly appreciated. Thank you.

This is a Demo table view.On tapping the table view cells a view is poped up with close button. And on pressing the close button the pop up view is closed.
import UIKit
class ViewController: UITableViewController {
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 numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell
cell.textLabel?.text = "Happy"
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("Cell\(indexPath.row) is selected")
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let popoverVC = storyBoard.instantiateViewControllerWithIdentifier("PopViewController") as! PopViewController
popoverVC.delegate = parentViewController as? InfoViewDelegate
let nav = UINavigationController(rootViewController: popoverVC)
nav.modalPresentationStyle = UIModalPresentationStyle.Popover
nav.navigationBar.hidden = true
self.presentViewController(nav, animated: true)
{
}
popoverVC.passingViewController = self
}
}
This is a PopUpViewController:
import UIKit
protocol InfoViewDelegate: class
{
func infoViewClicked(tag: Int)
}
class PopViewController :UIViewController
{
#IBOutlet weak var btnClose: UIButton!
var delegate = InfoViewDelegate?()
var passingViewController: UIViewController!
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.
}
override func viewWillAppear(animated: Bool) {
}
override func viewDidDisappear(animated: Bool) {
self.presentingViewController?.dismissViewControllerAnimated(true
, completion: {
})
}
/*
// 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 btnClicked(sender: UIButton) {
if(sender == self.btnClose)
{
self.delegate?.infoViewClicked(1)
self.presentingViewController?.dismissViewControllerAnimated(true
, completion: {
})
}
}
}

Related

Ios Swift 3 table view controller Constraints mess up after segueing back and forth in navigation controller

Im having an issue with my table view controller in swift 3. I have a very simple Cell configured as a prototype where an Image is on the left side of the cell, and a text label takes up 3/4 of the space after the image going towards the right side of the cell. Whenever I load the view, everything looks fine. However, when I either segue to a new view and then go back to that view from a back button on a navigation controller, or if I scroll up on the table to bring a cell out of the view and go back down the cells view totally screws up and moves the text label to the left and either gets rid of the image or overlays the image on top of the text label. I have seen one similar question on here, but the answers are in objective C or simply do not work. I have tried placing the loading logic in different methods such as viewWillAppear, viewDidLoad, etc. I have tried self.tableView.reload. I have also tried messing with the constraints manually and using tableViews estimatedHeight method. Can anyone help with this? Here is my class:
import UIKit
import Parse
var bikeList = [String]()
var customerBikeIDList = [String]()
var customerIndex: Int = 0;
class BikeListController: UITableViewController {
#IBAction func addBike(_ sender: Any) {
// let storyboard = UIStoryboard(name: "Main", bundle: nil)
//let vc = storyboard.instantiateViewController(withIdentifier: "addBikeVC")
//self.present(vc, animated: true, completion: nil)
self.performSegue(withIdentifier: "addBike", sender: self)
}
override func viewDidLoad() {
super.viewDidLoad()
//associate user to this device for notification usage
CommonUtils.addFCMTokenToParse()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
//was func viewWillAppear
override func viewWillAppear(_ animated: Bool) {
let query = PFQuery(className: "Bike")
if let userID = PFUser.current()?.objectId {
print("user ID: "+userID)
query.whereKey("userID", equalTo: userID)
query.findObjectsInBackground(block: { (objects: [PFObject]?, error: Error?) in
if error == nil {
if let objects = objects {
for object in objects {
print("printing items from parse query")
print(object["userID"])
print(object["model"])
if(!(bikeList.contains(object["model"] as! String))){
bikeList.append(object["model"] as! String)
customerBikeIDList.append(object.objectId!)
}
}
self.tableView.reloadData()
}
}else {
//there was an error
print("There was an error...")
}
})
}
}
//no reason for having this function here other then idk
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return (bikeList.count)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! BikeListCell
cell.theText.text = bikeList[indexPath.row]
// Configure the cell...
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
customerIndex = indexPath.row
self.performSegue(withIdentifier: "customerViewBike", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "addBike" {
let navVC = segue.destination as? UINavigationController
_ = navVC?.viewControllers.first as! AddBikeViewController
}
}
}
Here is the BikeListCell
import UIKit
class BikeListCell: UITableViewCell {
#IBOutlet var theText: UILabel!
#IBOutlet var bikePhoto: UIImageView!
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
}
}
Here is my constraints:

Unwind segue not unwinding

I'm trying to create a simple unwind segue but apparently I've made a mistake somewhere. The save button I would like to unwind reacts to pressing but doesn't unwind to the table view. Thanks in advance I appreciate it.
import UIKit
class NoteTableViewController: UITableViewController {
var notes = [Note]()
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
return cell
}
//ACTION
#IBAction func unwindToNoteList(sender: UIStoryboardSegue) {
if let sourceViewController = sender.source as? ViewController, let noteTaken = sourceViewController.noteTaken {
// Add a new meal.
let newIndexPath = IndexPath(row: notes.count, section: 0)
notes.append(noteTaken)
tableView.insertRows(at: [newIndexPath], with: .automatic)
}
}
}
and my view controller
import UIKit
import os.log
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var typeField: UITextField!
#IBOutlet weak var textDisplay: UILabel!
#IBOutlet weak var saveButton: UIBarButtonItem!
var noteTaken: Note?
func textFieldDidEndEditing(_ textField: UITextField) {
textDisplay.text = typeField.text
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// Hide the keyboard.
typeField.resignFirstResponder()
return true
}
override func viewDidLoad() {
super.viewDidLoad()
typeField.delegate = self
// Do any additional setup after loading the view, typically from a nib.
}
//NAV
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
// Configure the destination view controller only when the save button is pressed.
guard let button = sender as? UIBarButtonItem, button === saveButton else {
os_log("The save button was not pressed, cancelling", log: OSLog.default, type: .debug)
return
}
let note = typeField.text ?? ""
// Set the meal to be passed to MealTableViewController after the unwind segue.
noteTaken = Note(note: note)
}
#IBAction func cancelButton(_ sender: UIBarButtonItem) {
dismiss(animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
This is how I create my unwind segues:
Write the code for the unwind segue in the first View Controller:
#IBAction func unwindSegue(Segue: UIStoryboardSegue) {
// Run code when the view loads up
}
Create the segue in main.storyboard:
Give the segue an identifier:
then call it in code:
#IBAction func UnwindButton(_ sender: UIButton) {
performSegue(withIdentifier: "UnwindSegue", sender: UIButton())
}
Hope this helps!!!

Next VC is not showing

I have a segue going from the first VC clubSelectionViewController to the one shown below clubSummaryViewController, but I have to click back 2 times to get the next VC to show. What am I doing wrong?
import Foundation
import UIKit
class clubSelectionViewController: UIViewController, UITableViewDelegate {
var clubsForSelection = [clubObject]()
var clubForClubSummaryView = [clubObject]()
#IBAction func selectDanceClubs(sender: AnyObject) {
clubForClubSummaryView = clubDataFilter.removeStripClubsFrom(clubsForSelection)
self.performSegueWithIdentifier("ClubSummary", sender: self)
}
#IBAction func selectStripClubs(sender: AnyObject) {
clubForClubSummaryView = clubDataFilter.removeDanceClubsFrom(clubsForSelection)
self.performSegueWithIdentifier("ClubSummary", sender: self)
}
override func viewDidLoad() {
super.viewDidLoad()
// everytime screen loads it removes information to give blank screen it removes all clubs in array
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ClubSummary" {
let summaryView = segue.destinationViewController as! clubSummaryViewController
summaryView.clubDetails = [clubObject]()
summaryView.clubDetails = self.clubForClubSummaryView
}
}
}
Second VC
import UIKit
class clubSummaryViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var clubDetails = [clubObject]()
var selectedClub = clubObject()
#IBOutlet var clubSummaryTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
//Declare Delegate, Load TableView
clubSummaryTableView.delegate = self
//clubSummaryTableView.dataSource = self
clubSummaryTableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: TableViewDelegate
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.clubDetails.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.clubSummaryTableView.dequeueReusableCellWithIdentifier("SummaryCell")! as? clubSummaryCell
cell?.clubName.text = clubDetails[indexPath.row].clubName
cell?.clubAddress.text = clubDetails[indexPath.row].clubAddress
//TODO: insert image
cell?.clubPhoto.image = clubDetails[indexPath.row].clubImage.image
return cell!
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.selectedClub = self.clubDetails[indexPath.row]
self.performSegueWithIdentifier("ClubDetails", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ClubDetails"{
let clubDetailsView = segue.destinationViewController as? clubInfoViewController
clubDetailsView?.clubForDetails = self.selectedClub
}
}
}
I think the problem in the:
#IBAction func selectDanceClubs(sender: AnyObject) {
clubForClubSummaryView = clubDataFilter.removeStripClubsFrom(clubsForSelection)
self.performSegueWithIdentifier("ClubSummary", sender: self)
}
#IBAction func selectStripClubs(sender: AnyObject) {
clubForClubSummaryView = clubDataFilter.removeDanceClubsFrom(clubsForSelection)
self.performSegueWithIdentifier("ClubSummary", sender: self)
}
I not sure why you want these two func have the same SegueWithIdentifier
The reason might be that you have attached the segue from the button itself.
That means when you click on button the segue from the button is getting called, and since you have action of the button also, the segue is called again from the action method.
Means, the same segue is called twice.

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.
}
}

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.

Resources