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
}
}
Related
I am having an issue getting one simple variable from one class to another and it is beyond extremely frustrating :/...
Here is the deal I have two view controller classes named: ViewController.swift and ViewController2.swift
ViewController.swift is linked to a storyboard that has sort of an inventory bag that I have placed which is just an image. Then there is an #IBAction for when you click on the bag it opens up and the second storyboard pops into view. This is controlled by ViewController2.swift. All I am looking to do is simply pass the center of the bag image from ViewController to ViewController2 but I can't seem to get it to work any help would be greatly appreciated.
class ViewController: UIViewController {
#IBOutlet weak var InventoryBag: UIImageView!
var bagCenter:CGPoint = CGPoint(x: 0, y: 0)
override func viewDidLoad() {
super.viewDidLoad()
#IBAction func InventoryButtonTapped(sender: UIButton) {
self.InventoryBag.image = UIImage(named: "backpackimageopen")
bagCenter = self.InventoryBag.center
func transferViewControllerVariables() -> (CGPoint){
return bagCenter
}
When I print the bagCenter from this ViewController it works properly and gives me a correct value. So the bagCenter variable I would like to somehow pass over to ViewController2.swift.
Here is what I tried from ViewController2.swift but it never seems to work and always gives me a 0 rather than the actual value.
class ViewController2: UIViewController {
#IBOutlet weak var HideButton: UIButton!
#IBOutlet weak var InventoryCollection: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//Load the center of the inventory bag to this view controller to align the hide button.
var bagCenter = ViewController().transferViewControllerVariables()
}
But when I do this it always results in a 0 and I don't get the actual coords of the bag that are showing up in ViewController1.
Create a following variable in ViewController2
var previousViewController: ViewController!
Add following line of code in your ViewController Class
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){
if segue.destinationViewController .isKindOfClass(ViewController2){
let vc2 = segue.destinationViewController as! ViewController2
vc2.previousViewController = self
}
}
Now in viewDidLoad method of ViewController2 you can access bagCenter like below:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
var bagCenter = previousViewController.transferViewControllerVariables()
}
Try this in view Controller
class ViewController: UIViewController {
#IBOutlet weak var InventoryBag: UIImageView!
var bagCenter:CGPoint = CGPoint(x: 0, y: 0)
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func InventoryButtonTapped(sender: AnyObject) {
self.InventoryBag.image = UIImage(named:"MAKEUP_SHARE.jpg")
bagCenter = self.InventoryBag.center
performSegueWithIdentifier("Go", sender: self)
}
// Give a segue identifier in storyboard
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "yoursegueidentifier" {
let dvc = segue.destinationViewController as? ViewController2
dvc!.bagCenter = bagCenter
}
}
}
and in view controller2
class ViewController2: UIViewController {
var bagCenter:CGPoint!
override func viewDidLoad() {
super.viewDidLoad()
print(bagCenter)
}
}
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.
I am trying to pass var projectNumber from ViewController to Project1ViewController via segue and save it as var projectNum. Then use projectNum to update the labels in Project1ViewController. The segue and action/outlets are all set up. The app runs fluently (no errors), however, projectNum in Project1ViewController is not getting the projectNumber value and making it projectNum.
How do I pass the projectNumber value from ViewController to Project1ViewController and save it in projectNum? I've seen tutorials that describe similar actions being performed via delegates, but I'm unsure if delegates are applicable to my question. Any feedback helps.
ViewController
import UIKit
class ViewController: UIViewController{
var projectNumber:String = ""
#IBOutlet var projectButton1 : UIButton!
#IBOutlet var projectButton2 : UIButton!
#IBOutlet var projectButton3 : UIButton!
#IBOutlet var projectButton4 : UIButton!
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 updateLabels(sender: UIButton!) {
projectNumber = String(sender.tag)
println(projectNumber)
sender.setTitle(String(projectNumber), forState: UIControlState.Normal)
func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
//if user presses Project 3921 button
if segue.identifier == "Project3921Segue"
{
if var destinationVC = segue.destinationViewController as? Project1ViewController{
destinationVC.projectNum = projectNumber
}
}
//if user presses Project 3922 button
else if segue.identifier == "Project3922Segue"
{
if var destinationVC = segue.destinationViewController as? Project1ViewController{
destinationVC.projectNum = projectNumber
}
}
//if user presses Project 3923 button
else if segue.identifier == "Project3923Segue"
{
if var destinationVC = segue.destinationViewController as? Project1ViewController{
destinationVC.projectNum = projectNumber
}
}
//otherwise user presses Project 3924 button
else if segue.identifier == "Project3924Segue"
{
if var destinationVC = segue.destinationViewController as? Project1ViewController{
destinationVC.projectNum = projectNumber
}
}
}
}
}
Project1ViewController
import UIKit
class Project1ViewController: UIViewController {
var projectNum:String!
#IBOutlet var projectNumLabel: UILabel!
#IBOutlet var projectNumTitle: UINavigationItem!
override func viewDidLoad() {
super.viewDidLoad()
projectNumLabel.text = projectNum
projectNumTitle.title = projectNum
println(projectNum)
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Thanks!
You are defining prepareForSegueinside the button action function. It is a ViewController function to be overridden.
Your solution can be way more simpler:
class ViewController: UIViewController{
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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if var destinationVC = segue.destinationViewController as? Project1ViewController{
destinationVC.projectNum = segue.identifier
}
}
}
Note you do not need the button outlets, since you just configure them in the storyboard with the proper segue identifier. Unless you need some other custom action to be triggered by the buttons.
And:
class Project1ViewController: UIViewController {
var projectNum:String!
#IBOutlet var projectNumLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
projectNumLabel.text = projectNum
self.title = projectNum
println(projectNum)
}
}
Note I just set the title property of Project1ViewController in order to present the projectNum as the title in the navigation controller. I assume your controllers are embedded in a navigation controller and the ViewController's buttons has show segues to Project1ViewController.
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.
I am trying out apple's new language swift in Xcode 6 beta. I am trying to programmatically switch views when a table view cell is pressed, although all it does is pull up a blank black screen. In my code, I commented out the things that didn't work. They would just make the iOS simulator crash. my code:
// ViewController.swift
// Step-By-Step Tip Calculator
// Created by Dani Smith on 6/17/14.
// Copyright (c) 2014 Dani Smith Productions. All rights reserved.
import UIKit
var billTotalPostTax = 0
class BillInfoViewController: UIViewController {
//outlets
#IBOutlet var totalTextField: UITextField
#IBOutlet var taxPctLabel: UILabel
#IBOutlet var resultsTextView: UITextView
#IBOutlet var taxPctTextField : UITextField
//variables
var billTotalVar = ""
var taxPctVar = ""
//actions
override func viewDidLoad() {
super.viewDidLoad()
refreshUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func stepOneNextPressed(sender : AnyObject)
{
billTotalVar = totalTextField.text
taxPctVar = taxPctTextField.text
}
#IBAction func calculateTipped(sender : AnyObject)
{
tipCalc.total = Double(totalTextField.text.bridgeToObjectiveC().doubleValue)
let possibleTips = tipCalc.returnPossibleTips()
var results = ""
for (tipPct, tipValue) in possibleTips
{
results += "\(tipPct)%: \(tipValue)\n"
}
resultsTextView.text = results
}
/*
#IBAction func taxPercentageChanged(sender : AnyObject)
{
tipCalc.taxPct = String(taxPctTextField.text) / 100
refreshUI()
}*/
#IBAction func viewTapped(sender : AnyObject)
{
totalTextField.resignFirstResponder()
}
let tipCalc = TipCalculatorModel(total: 33.25, taxPct: 0.06)
func refreshUI()
{
//totalTextField.text = String(tipCalc.total)
}
}
class RestaurantTableViewController: UITableViewController
{
override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!)
{
let row = indexPath?.row
println(row)
//let vc:BillInfoViewController = BillInfoViewController()
//let vc = self.storyboard.instantiateViewControllerWithIdentifier("billInfo") as UINavigationController
//self.presentViewController(vc, animated: true, completion: nil)
}
}
Thank you so much for all of your help.
I just figured it out. I had to make
let vc = self.storyboard.instantiateViewControllerWithIdentifier("billInfo")`
to be
let vc : AnyObject! = self.storyboard.instantiateViewControllerWithIdentifier("billInfo")
to silence a warning. I then changed presentViewController to showViewController, and it worked. Here is my completed class:
class RestaurantTableViewController: UITableViewController
{
override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!)
{
let row = indexPath?.row
println(row)
let vc : AnyObject! = self.storyboard.instantiateViewControllerWithIdentifier("billInfo")
self.showViewController(vc as UIViewController, sender: vc)
}
}
let vc = self.storyboard.instantiateViewControllerWithIdentifier("billInfo") as! BillInfoViewController
self.presentViewController(vc, animated: true, completion: nil)
LE: downcast added