Passing variables between classes in Swift - xcode

I have a table view controller named ThirdViewController which displays a list of transactions. When a user presses the add button, the app segues to the FifthViewController where they can enter the transaction name, value and date. I am trying to get this data entered in FifthViewController into a class named ArrayData so that I can add it to the array which will then add the payment to the ThirdViewController table view.
This is my code for the ThirdViewController.swift:
var arrayObject = ArrayData()
class ThirdViewController: UITableViewController {
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.
}
// #pragma mark - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return arrayObject.paymentsArray().count
}
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell:CustomTransactionTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as CustomTransactionTableViewCell
cell.paymentNameLabel.text = (arrayObject.paymentsArray().objectAtIndex(indexPath.row)) as String
cell.costLabel.text = (arrayObject.costArray().objectAtIndex(indexPath.row)) as String
cell.dateLabel.text = (arrayObject.dateArray().objectAtIndex(indexPath.row)) as String
return cell
}
}
This is the code for arrayData.swift:
class ArrayData: NSObject {
func paymentsArray() -> NSMutableArray {
var arrayDataPayments: NSMutableArray = ["Test"]
return arrayDataPayments
}
func costArray() -> NSMutableArray {
var arrayDataCost: NSMutableArray = ["£100"]
return arrayDataCost
}
func dateArray() -> NSMutableArray {
var arrayDataDate: NSMutableArray = ["12/07/14"]
return arrayDataDate
}
}
And this is the code for FifthViewController:
class FifthViewController: UIViewController {
#IBOutlet var transactionNameInput : UITextField
#IBOutlet var transactionDateInput : UITextField
#IBOutlet var transactionValueInput : UITextField
#IBOutlet var addBackButton : UIButton
#IBAction func addTransactionButton(sender : AnyObject) {
self.navigationController.popToRootViewControllerAnimated(true)
var transactionName = transactionNameInput.text
var transactionDate = transactionDateInput.text
var transactionValue = transactionValueInput.text
}
#IBAction func viewTapped(sender : AnyObject) {
//Closes keyboard when user touches screen
transactionDateInput.resignFirstResponder()
transactionNameInput.resignFirstResponder()
transactionValueInput.resignFirstResponder()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
How can I get the variables from the FifthViewController to the ArrayData class so they can be added to the arrays? This might be very simple but I'm new to Xcode and obviously Swift.
Any help would be greatly appreciated.

The methods in your ArrayData class are awkwardly implemented as each invocation returns a new array. Perhaps this is what you really want, but it is unusual (and you've noted that you are new to Xcode and Swift and thus I suspect it isn't really what you want). A more normal implementation would be :
class ArrayData: NSObject {
var arrayDataPayments: NSMutableArray = ["Test"]
var arrayDataCost: NSMutableArray = ["£100"]
var arrayDataDate: NSMutableArray = ["12/07/14"]
func paymentsArray() -> NSMutableArray { return arrayDataPayments }
func costArray() -> NSMutableArray { return arrayDataCost }
func dateArray() -> NSMutableArray { return arrayDataDate }
}
Now, I'm not saying that this is going to solve your bigger issue of getting the data in an out of your controller; but, I suspect that the above is a better start.

Related

Xcode 7 - Cell content not displayed into an empty label

I'm trying to display a cell content into an empty UILabel, but after I upgraded to Xcode 7, the content didn't show up. I was following the same mechanism and it worked on Xcode 6, but since I'm new to Swift I may have something wrong in the code.
TableViewController:
import UIKit
class TableViewController: UITableViewController {
struct dataModel {
var name:String
var val:Double
}
let foods = [dataModel(name: "name1", val: 3.3),
dataModel(name: "name2", val: 5.5)]
#IBOutlet var table: UITableView!
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 numberOfSectionsInTableView(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 foods.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
// Configure the cell...
let foodCell = foods[indexPath.row]
cell.textLabel?.text = foodCell.name
return cell
}
var valueToPass:String!
var valueInt:Int!
override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
let indexPath = tableView.indexPathForSelectedRow;
let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!;
valueToPass = currentCell.textLabel!.text
performSegueWithIdentifier("showCalc", sender: self)
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "showCalc") {
let viewController = segue.destinationViewController as! calcViewController
viewController.passedValue = valueToPass
}
}
}
ViewController where I want to display the tapped cell into an empty label:
import UIKit
class calcViewController: UIViewController {
#IBOutlet var text: UILabel!
#IBOutlet var empty1: UILabel!
var passedValue:String!
override func viewWillAppear(animated: Bool) {
empty1.text = passedValue
}
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.
}
As a result, there is no error, but there is nothing displayed inside the empty label.
The other thing I want to achieve is to display the Int value into another label and then do some calculations, but this would be another question. Thanks in advance!
There are several issues in this code. First you are obviously missing some closing braces. But I assume this is a copy-paste error.
Why do you use didDeselectRowAtIndexPath? Don't you have a segue from the table view cell to the next controller? Then you should get the text label in prepareForSegue by using tableView.indexPathForSelectedRow.
If you like to keep it this way you should use didSelect... in stead of didDeselect....
You should take the value you want to pass to the next view controller direct from the data and not from the cell. You have the data you present in the table in the foods array.
Class names should always start with a capital letter. ALWAYS!
Having the data model within the controller is poor design. You should have the struct separated in its own file. In this case you could even hand the complete data object to the next view controller.

Save UITableView names to array on button action

I want to save the names that are filled in UITableView to an array
var mineSpillere = [String]()
How can I do this on buttonAction?
This is button action for how i add names to tableview:
#IBAction func addButtonAction(sender: AnyObject) {
mineSpillere.append(namesTextBox.text)
myTableView.reloadData()
}
and also here code:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = self.myTableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
cell.textLabel!.text = self.mineSpillere[indexPath.row]
return cell;
}
That only when I press the "back" button in the application, the names from the UITableView will be saved in an array.
I am going to access these names from another view controller also, so i need them to be saved as an array.
Okay so it looks like you have all the data in the mineSpillere array already as you're using cell.textLabel!.text = self.mineSpillere[indexPath.row] so to get that array back to the first view controller. You could use the following code in the view controller that is being presented when the 'back' button is being pressed:
class FirstViewController: UIViewController,SecondViewControllerDelegate {
var mineSpillereCopyFromSecondVC = [String]()
func presentSecondViewController() {
// Im not sure the class name for you're second view
// where the tableView is located.
var secondVC: SecondViewController = SecondViewController();
secondVC.delegate = self
// Also not too sure on how you're presenting the `SecondViewController` so I'm goingg to leave that empty.
// The important part is just above us.
}
func passMineSpillere(mineSpillere: [String]) {
// This class now has the mineSpiller array of name.
self.mineSpillereCopyFromSecondVC = mineSpillere
}
}
And then in you SecondViewController where the tableView is located you could add the following code.
import UIKit
protocol SecondViewControllerDelegate {
func passMineSpillere(mineSpillere:[String])
}
class SecondViewController: UIViewController {
var delegate: SecondViewControllerDelegate?
var mineSpillere = [String]()
// This will be called when the 'back' button is pressed.
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
// Pass the mineSpillere array back to the delegate
// which is the firstViewController instance.
self.delegate?.passMineSpillere(self.mineSpillere)
}
}

"type" viewController does not conform to protocol "UITableViewDataSource"

I keep getting this error for some reason.
"type" viewController does not conform to protocol "UITableViewDataSource"
I know that this has been covered a million times and there are even videos explaining why this problem occurs, but for some reason I can't fix it and can't figure out exactly what it is that I have done wrong.
Here is my code:
//
// ViewController.swift
// ChatApp
//
// Created by K on 17/03/2015.
// Copyright (c) 2015 Krazy88 All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
#IBOutlet weak var dockViewHeightConstraint: NSLayoutConstraint!
#IBOutlet weak var sendButton: UIButton!
#IBOutlet weak var messageTextField: UITextField!
#IBOutlet weak var messageTableView: UITableView!
var messagesArray:[String] = [String]()
var delegate: UITableViewDataSource? = nil
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.messageTableView.delegate = self
self.messageTableView.dataSource = self
// Set self as the delegate for the textfield
self.messageTextField.delegate = self
//Add a tap gesture recognizer to the tableview
let tapGesture:UITapGestureRecognizer = UITapGestureRecognizer(target:self, action: "tableViewTapped")
self.messageTableView.addGestureRecognizer(tapGesture)
// Retrieve messages from Parse
self.retreiveMessages()
}
override func didReceiveMemoryWarning(){
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func sendButtonTapped(sender: UIButton) {
// Send button is tapped
// Call the end editing method for the text field
self.messageTextField.endEditing(true)
//Disable the send button and textfield
self.messageTextField.enabled = false
self.sendButton.enabled = false
// Create a PFObject
var newMessageObject:PFObject = PFObject(className: "Message")
// Set the Text key to the text of the messageTextField
newMessageObject["Text"] = self.messageTextField.text
// Save the PFObject
newMessageObject.saveInBackgroundWithBlock { (success:Bool, error:NSError!) -> Void in
if (success == true) {
//Message has been saved!
// TODO: Retrieve the latest messages and reload the table
NSLog("Message saved successfully.")
}
else {
// Something bad happened.
NSLog(error.description)
}
// Enable the textfield and send button
self.sendButton.enabled = true
self.messageTextField.enabled = true
self.messageTextField.text = ""
}
}
func retreiveMessages() {
// Create a new PFQuery
var query:PFQuery = PFQuery(className: "Message")
// Call findobjectsinbackground
query.findObjectsInBackgroundWithBlock { (objects:[AnyObject]!, error:NSError!) -> Void in
// clear the messageArray
self.messagesArray = [String]()
// Loop through the objects array
for messageObject in objects {
// Retrieve the Text column of each PFObject
let messageText:String? = (messageObject as PFObject)["Text"] as? String
// Assign it into our messagesArray
if messageText != nil {
self.messagesArray.append(messageText!)
}
}
// Reload the tableview
self.messageTableView.reloadData()
// Reload the tableview
}
func tableViewTapped() {
// Force the textfield to end editing
self.messageTextField.endEditing(true)
}
// MARK: Textfield Delegate Methods
func textFieldDidBeginEditing(textField: UITextField) {
// Perform an animation to grow the dockview
self.view.layoutIfNeeded()
UIView.animateWithDuration(0.5, animations: {
self.dockViewHeightConstraint.constant = 350
self.view.layoutIfNeeded()
} , completion: nil)
}
func textFieldDidEndEditing(textField:UITextField) {
// Perform an animation to grow the dockview
self.view.layoutIfNeeded()
UIView.animateWithDuration(0.5, animations: {
self.dockViewHeightConstraint.constant = 60
self.view.layoutIfNeeded()
}, completion: nil)
}
// MARK: TableView Delegate Methods
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Create a table cell
let cell = self.messageTableView.dequeueReusableCellWithIdentifier("MessageCell") as UITableViewCell
// Customize the cell
cell.textLabel.text = self.messagesArray[indexPath.row]
//Return the cell
return cell
}
func TableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messagesArray.count
}
}
}
Any helps tips or suggestion will be much appreciated as I have tried everything!
thanks for reading
Kurando
Your UITableViewDataSource #required delegates are inside retreiveMessages(). Fix the position of that second last bracket..!!
Here is your correct code :
import Foundation
import UIKit
class ViewController : UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {
#IBOutlet weak var dockViewHeightConstraint: NSLayoutConstraint!
#IBOutlet weak var sendButton: UIButton!
#IBOutlet weak var messageTextField: UITextField!
#IBOutlet weak var messageTableView: UITableView!
var messagesArray:[String] = [String]()
var delegate: UITableViewDataSource? = nil
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
messageTableView.delegate = self
messageTableView.dataSource = self
// Set self as the delegate for the textfield
self.messageTextField.delegate = self
//Add a tap gesture recognizer to the tableview
let tapGesture:UITapGestureRecognizer = UITapGestureRecognizer(target:self, action: "tableViewTapped")
self.messageTableView.addGestureRecognizer(tapGesture)
// Retrieve messages from Parse
self.retreiveMessages()
}
override func didReceiveMemoryWarning(){
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func sendButtonTapped(sender: UIButton) {
// Send button is tapped
// Call the end editing method for the text field
self.messageTextField.endEditing(true)
//Disable the send button and textfield
self.messageTextField.enabled = false
self.sendButton.enabled = false
// Create a PFObject
var newMessageObject:PFObject = PFObject(className: "Message")
// Set the Text key to the text of the messageTextField
newMessageObject["Text"] = self.messageTextField.text
// Save the PFObject
newMessageObject.saveInBackgroundWithBlock { (success:Bool, error:NSError!) -> Void in
if (success == true) {
//Message has been saved!
// TODO: Retrieve the latest messages and reload the table
NSLog("Message saved successfully.")
}
else {
// Something bad happened.
NSLog(error.description)
}
// Enable the textfield and send button
self.sendButton.enabled = true
self.messageTextField.enabled = true
self.messageTextField.text = ""
}
}
func retreiveMessages() {
// Create a new PFQuery
var query:PFQuery = PFQuery(className: "Message")
// Call findobjectsinbackground
query.findObjectsInBackgroundWithBlock { (objects:[AnyObject]!, error:NSError!) -> Void in
// clear the messageArray
self.messagesArray = [String]()
// Loop through the objects array
for messageObject in objects {
// Retrieve the Text column of each PFObject
let messageText:String? = (messageObject as PFObject)["Text"] as? String
// Assign it into our messagesArray
if messageText != nil {
self.messagesArray.append(messageText!)
}
}
// Reload the tableview
self.messageTableView.reloadData()
// Reload the tableview
}
}
func tableViewTapped() {
// Force the textfield to end editing
self.messageTextField.endEditing(true)
}
// MARK: Textfield Delegate Methods
func textFieldDidBeginEditing(textField: UITextField) {
// Perform an animation to grow the dockview
self.view.layoutIfNeeded()
UIView.animateWithDuration(0.5, animations: {
self.dockViewHeightConstraint.constant = 350
self.view.layoutIfNeeded()
} , completion: nil)
}
func textFieldDidEndEditing(textField:UITextField) {
// Perform an animation to grow the dockview
self.view.layoutIfNeeded()
UIView.animateWithDuration(0.5, animations: {
self.dockViewHeightConstraint.constant = 60
self.view.layoutIfNeeded()
}, completion: nil)
}
// MARK: TableView Delegate Methods
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return messagesArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Create a table cell
let cell = self.messageTableView.dequeueReusableCellWithIdentifier("MessageCell") as UITableViewCell
// Customize the cell
cell.textLabel?.text = self.messagesArray[indexPath.row]
//Return the cell
return cell
}
}
Copy from here.
And always make sure to call numberOfRowsInSection before cellForRowAtIndexPath.

TableViewController and CustomCell using Swift

I'm trying to populate a TableViewController with data and display it using a CustomCell so I can have two labels and a button on each row.
I have placed the two labels and the button in the PrototypeCell within the Main Storyboard.
I have created a CustomCellTableViewCell class:
import UIKit
class CustomCellTableViewCell: UITableViewCell {
#IBOutlet var customCellLabel1: [UILabel]!
#IBOutlet var customCellLabel2: [UILabel]!
#IBOutlet var CustomCellButton: [UIButton]!
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
}
}
and within my UITableViewController I have:
var DevicesList: Array<AnyObject>=[]
var ii: Int = 1
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let CellID : NSString = "DeviceCell"
var cell : CustomCellTableViewCell = tableView.dequeueReusableCellWithIdentifier(CellID) as CustomCellTableViewCell
if DevicesList.count > 0 {
var data: NSManagedObject = DevicesList[indexPath.row] as NSManagedObject
cell.customCellLabel1[indexPath.row].text = data.valueForKeyPath("name") as? String
println("loading row \(ii) loaded!")
ii++
} else {
println("nothing loaded...?")
}
println("cell loaded")
return cell
}
when I run it though the first row is loaded but then I get a:
loading row 1 loaded!
cell loaded
fatal error: Array index out of range
The guilty line is shown as this one:
cell.customCellLabel1[indexPath.row].text = data.valueForKeyPath("name") as? String
I have 7 rows to load so somewhere I need to append the labels/button array and if so where/how do I do it?
Thanks!
Kostas
Just for future searches here is how it was solved:
Created new class:
import UIKit
class DeviceCustomCell: UITableViewCell {
#IBOutlet var myLabel1: UILabel!
#IBOutlet var myLabel2: UILabel!
#IBOutlet var myButton: UIButton!
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
}
#IBAction func PressButton(sender: AnyObject) {
myButton.setTitle("OFF", forState: UIControlState.Normal)
}
}
Linked the labels and button from the Main storyboard to the two variables (New Reference Outlet).
Important to have the Identifier as "DeviceCustomCell" for the Prototype Cell and then modify the function:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let CellID : NSString = "DeviceCustomCell"
var cell = tableView.dequeueReusableCellWithIdentifier("DeviceCustomCell") as DeviceCustomCell
if DevicesList.count > 0 {
var data: NSManagedObject = DevicesList[indexPath.row] as NSManagedObject
var devicename : String = data.valueForKeyPath("name") as String
var lastchanged: String = data.valueForKeyPath("lastChangedRFC822") as String
cell.myLabel1.text = devicename
cell.myLabel2.text = lastchanged
println("loading row \(ii) loading...")
ii++
return cell
} else {
println("nothing loaded...?")
}
return cell
}
This now works nicely!
Important is to understand this line:
var cell = tableView.dequeueReusableCellWithIdentifier("DeviceCustomCell") as DeviceCustomCell
as it holds the key to success! :)
Kostas

Updates Labels in Swift when using popoverController

I have a question about swift,
I made a popover controller in a UIViewController,which display a list of books
and when the user click on one of the books, the label on the viewController should be updated with the name of the selected book.
But in my case when I select a name of a book, the label does not update
here is the code :
// View Controller
import UIKit
class ViewController: UIViewController,UIPopoverControllerDelegate {
var popoverController : UIPopoverController? = nil
#IBOutlet var bookName : UILabel
var BookNameString : String?{
didSet{
configureView()
}
}
func configureView() {
// Update the user interface for the detail item.
if let detail = self.BookNameString {
if let label = bookName {
label.text = detail
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func Click(sender : UIButton) {
var tableView:TableViewController = TableViewController(style: UITableViewStyle.Plain)
var popoverContent:UINavigationController = UINavigationController(rootViewController: tableView)
self.popoverController = UIPopoverController(contentViewController: popoverContent)
self.popoverController!.delegate = self
self.popoverController!.presentPopoverFromRect(sender.frame, inView: self.view, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
and here is the code of the TableViewController when a row is selected:
// TableViewController
override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!){
var storyboard = UIStoryboard(name: "Main", bundle: nil)
var details = storyboard.instantiateViewControllerWithIdentifier("ViewController") as ViewController
var keyString = bookSectionKeys[indexPath.section]
var bookValues = book.booksLetters[keyString]!
var selectedBookString = bookValues[indexPath.row]
var selectedBookValues = book.bookDictionary[selectedBookString]!
details.BookNameString = selectedBookString
}
I was able to solve this problem a few weeks ago and I want to share the solution with you :)
I solve it using protocols.
OK Here what I did in details:
First I created a protocol in the view that I want it to display inside the popover and I named the protocol "DismissPopoverDelegate"
protocol DismissPopoverDelegate{
func didSelectBook(SelectedBook:String)
}
Then I declared a variable of type DismissPopoverDelegate and name it "delegate"
var delegate: DismissPopoverDelegate?
Then in the didSelectRowAtIndexMethod:
override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!){
var keyString = bookSectionKeys[indexPath.section]
var bookValues = book.booksLetters[keyString]!
var selectedBookString = bookValues[indexPath.row]
delegate?.didSelectBook(selectedBookString)
}
After that inside the View that contains the popover (View Controller), I set the delegate of the view:
class ViewController: UIViewController, DismissPopOverDelegate, UIPopoverControllerDelegate{
Then to make the view confirm to the protocol DismissPopOverDelegate, I implement the method "didSelectBook" Inside the view:
func didSelectBook(SelectedBook:String){
popoverController!.dismissPopoverAnimated(true) // This is Optional
bookName.text = SelectedBook // Make the label text equal to the selected book From the table
}
Finally, I set the delegate to the tableView to View Controller
tableView.delegate = self
That's it :)
Here is the full code of the viewController that contains the popover
import UIKit
class ViewController: UIViewController, DismissPopOverDelegate, UIPopoverControllerDelegate{
#IBOutlet var booksbarButton : UIBarButtonItem
#IBOutlet var bookName : UILabel
var popoverController : UIPopoverController? = nil
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func showTableView(sender : UIBarButtonItem) {
var tableView:TableViewController = TableViewController(style: UITableViewStyle.Plain)
tableView.delegate = self
var popoverContent:UINavigationController = UINavigationController(rootViewController: tableView)
self.popoverController = UIPopoverController(contentViewController: popoverContent)
popoverController!.delegate = self
self.popoverController!.presentPopoverFromBarButtonItem(booksbarButton, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true)
}
func didSelectBook(SelectedBook:String){
popoverController!.dismissPopoverAnimated(true)
bookName.text = SelectedBook
}
}

Resources