Delegate error in swift 2 - swift2

I'm having trouble passing data after run App.I'm pretty much trying to change a label from the previous view controller after selecting a table view cell
Could anyone help me go about there error?
view controller
class AircraftSearch: UIViewController ,SendbackDelegate{
#IBOutlet weak var Mabda: UIButton!
#IBOutlet weak var maghsad: UIButton!
#IBOutlet weak var labelcity: UILabel!
var Airurl = NSURL()
var ScrOrDstArray = [MabdaAndMaghsad]()
var origin = [String]() // save mabda
var purpose = [String]() // save maghsad
var sendDataToTableview = [String]()
override func viewDidLoad() {
super.viewDidLoad()
GetPassCity()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func selectMabda(sender: AnyObject) {
sendDataToTableview = origin
performSegueWithIdentifier("SelectedCellSegue", sender: sender)
}
#IBAction func selectMaghsad(sender: AnyObject) {
sendDataToTableview = purpose
print(sendDataToTableview)
performSegueWithIdentifier("SelectedCellSegue", sender: sender)
}
func originAndpurpose() {
let dataCity = ScrOrDstArray
for i in dataCity{
if i.SrcOrDst == true{
origin.append(i.Name)
}else{
purpose.append(i.Name)
}
}
}
func GetPassCity(){
let actInd : UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(0,0, 50, 50)) as UIActivityIndicatorView
actInd.center = self.view.center
actInd.hidesWhenStopped = true
actInd.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
view.addSubview(actInd)
actInd.startAnimating()
NSURLSession.sharedSession().dataTaskWithURL(Airurl){ ( data ,response ,error) in
if error != nil{
print("A")
print(error!)
}else{
do{
//readin data from Server
let posts = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! [[String:AnyObject]]
//save data
for post in posts{
var postCity:MabdaAndMaghsad?
if let Id = post["Id"] as? Int ,
let nameCity = post["Name"] as? String ,
let SrcOrDst = post["SrcOrDst"] as? Bool
{
postCity = MabdaAndMaghsad(ID: Id, Name: nameCity, SrcOrDst: SrcOrDst)
}
self.ScrOrDstArray.append(postCity!)
}
//===============
dispatch_async(dispatch_get_main_queue()){
actInd.stopAnimating()
self.originAndpurpose()
print(self.origin)
print("=======")
// print(self.purpose)
}
}catch let error as NSError{
print("B")
print(error)
}
}
}.resume()
}
func sendNameToPreviousVC(SelectCity: String) {
labelcity.text = SelectCity
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "SelectedCellSegue" {
if let VC = segue.destinationViewController as? SelectedCity {
VC.toTake = sendDataToTableview
VC.delegate = self
}
}
}
}
and tableview Controller
import UIKit
protocol SendbackDelegate:class {
func sendNameToPreviousVC(City:String)
}
class SelectedCity: UITableViewController {
var toTake = [String]()
var selecteCity = String()
weak var delegate: SendbackDelegate? = nil
override func viewDidLoad() {
super.viewDidLoad()
}
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 toTake.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("stcell", forIndexPath: indexPath) as? mAndMCell
let nameCity = toTake[indexPath.row]
print(nameCity)
cell!.nameCityLabel.text = nameCity
return cell!
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
let indexPath = tableView.indexPathForSelectedRow!
let currentCell = tableView.cellForRowAtIndexPath(indexPath) as! mAndMCell!
selecteCity = currentCell.nameCityLabel!.text as String!
sendBackIdCity(selecteCity)
navigationController?.popViewControllerAnimated(true)
}
func sendBackIdCity(name: String){
self.delegate?.sendNameToPreviousVC(name)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "backCitySegue"{
var VCOne = segue.destinationViewController as? AircraftSearch
VCOne.delegate = self
}
}
}
error is line VCOne.delegate = self
error = Value of type 'AircraftSearch?' has no member 'delegate'

The line should probably be
self.delegate = VCOne
since self is the SelectedCity which has the delegate property and VCOne is of type AircraftSearch and therefore is a SendbackDelegate!

Related

Select and Pass Multiple Images in an Api request Swift

Im new to swift and im trying to figure out a way to select multiple images and pass them as array in a API request.I tried to use DKImagePickerController, in which im able to select multiple images and even preview them but i have no idea how to pass them to an api as an array.
The code is as follows:
import UIKit
class CameraTabViewController: UIViewController,UICollectionViewDataSource, UICollectionViewDelegate{
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func saveCamBtn(_ sender: Any) {
let parent = self.parent as! DiaryEntryViewController
parent.CameraView.isHidden = true
}
#IBAction func selectPhotoBtn(_ sender: Any) {
let pickerController = DKImagePickerController()
pickerController.defaultSelectedAssets = self.assets
pickerController.didCancel = { ()
}
pickerController.didSelectAssets = { [unowned self] (assets: [DKAsset]) in
self.updateAssets(assets: assets)
}
self.present(pickerController, animated: true)
}
var pickerController: DKImagePickerController!
var assets: [DKAsset]?
#IBOutlet var previewView: UICollectionView!
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
return self.assets?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let asset = self.assets![indexPath.row]
var cell: UICollectionViewCell?
var imageView: UIImageView?
if asset.isVideo {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CellVideo", for: indexPath)
imageView = cell?.contentView.viewWithTag(1) as? UIImageView
} else {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CellImage", for: indexPath)
imageView = cell?.contentView.viewWithTag(1) as? UIImageView
}
if let cell = cell, let imageView = imageView {
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
let tag = indexPath.row + 1
cell.tag = tag
asset.fetchImageWithSize(layout.itemSize.toPixel(), completeBlock: { image, info in
if cell.tag == tag {
imageView.image = image
}
})
}
return cell!
}
func updateAssets(assets: [DKAsset]) {
self.assets = assets
self.previewView?.reloadData()
}
}

How to make collectionView stop blinking

I have a problem with my collection view, which gives me a 'blink' a second after the view gets appeared on the screen.
Could it be the viewDidLoad or the viewDidAppear that causes this?
This is my current Swift code:
class HomeViewController: UIViewController
{
// MARK: IBOutlets
#IBOutlet weak var backgroundImageView: UIImageView!
#IBOutlet weak var collectionView: UICollectionView!
#IBOutlet weak var currentUserProfileImageButton: UIButton!
#IBOutlet weak var currentUserFullNameButton: UIButton!
// MARK: - UICollectionViewDataSource
private var interests = [Interest]()
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if PFUser.currentUser() == nil {
// the user hasn't logged in yet
showLogin()
} else {
// the user logged in, do something else
fetchInterests()
let center = NSNotificationCenter.defaultCenter()
let queue = NSOperationQueue.mainQueue()
center.addObserverForName("NewInterestCreated", object: nil, queue: queue, usingBlock: { (notification) -> Void in
if let newInterest = notification.userInfo?["newInterestObject"] as? Interest {
if !self.interestWasDisplayed(newInterest) {
self.interests.insert(newInterest, atIndex: 0)
self.collectionView.reloadData()
}
}
})
}
}
func interestWasDisplayed(newInterest: Interest) -> Bool {
for interest in interests {
if interest.objectId! == newInterest.objectId! {
return true
}
}
return false
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if UIScreen.mainScreen().bounds.size.height == 480.0 {
let flowLayout = self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout
flowLayout.itemSize = CGSizeMake(250.0, 300.0)
}
configureUserProfile()
}
func configureUserProfile()
{
// configure image button
currentUserProfileImageButton.contentMode = UIViewContentMode.ScaleAspectFill
currentUserProfileImageButton.layer.cornerRadius = currentUserProfileImageButton.bounds.width / 2
currentUserProfileImageButton.layer.masksToBounds = true
}
private struct Storyboard {
static let CellIdentifier = "Interest Cell"
}
#IBAction func userProfileButtonClicked()
{
PFUser.logOut()
showLogin()
}
// MARK: - Fetch Data From Parse
func fetchInterests()
{
let currentUser = User.currentUser()!
let interestIds = currentUser.interestIds
if interestIds?.count > 0
{
let interestQuery = PFQuery(className: Interest.parseClassName())
interestQuery.orderByDescending("updatedAt")
interestQuery.cachePolicy = PFCachePolicy.NetworkElseCache
interestQuery.whereKey("objectId", containedIn: interestIds)
interestQuery.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if error == nil {
if let interestObjects = objects as [PFObject]? {
self.interests.removeAll()
for interestObject in interestObjects {
let interest = interestObject as! Interest
self.interests.append(interest)
}
self.collectionView.reloadData()
}
} else {
print("\(error!.localizedDescription)")
}
})
}
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "Show Interest" {
let cell = sender as! InterestCollectionViewCell
let interest = cell.interest
let navigationViewController = segue.destinationViewController as! UINavigationController
let interestViewController = navigationViewController.topViewController as! InterestViewController
interestViewController.interest = interest
} else if segue.identifier == "CreateNewInterest" {
_ = segue.destinationViewController as! NewInterestViewController
} else if segue.identifier == "Show Discover" {
_ = segue.destinationViewController as! DiscoverViewController
}
}
func showLogin()
{
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let welcomeNavigationVC = storyboard.instantiateViewControllerWithIdentifier("WelcomeNavigationViewController") as! UINavigationController
self.presentViewController(welcomeNavigationVC, animated: true, completion: nil)
}
}
extension HomeViewController : UICollectionViewDataSource{
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int
{
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return interests.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(Storyboard.CellIdentifier, forIndexPath: indexPath) as! InterestCollectionViewCell
cell.interest = self.interests[indexPath.item]
return cell
}
}
extension HomeViewController : UIScrollViewDelegate{
func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>)
{
let layout = self.collectionView?.collectionViewLayout as! UICollectionViewFlowLayout
let cellWidthIncludingSpacing = layout.itemSize.width + layout.minimumLineSpacing
var offset = targetContentOffset.memory
let index = (offset.x + scrollView.contentInset.left) / cellWidthIncludingSpacing
let roundedIndex = round(index)
offset = CGPoint(x: roundedIndex * cellWidthIncludingSpacing - scrollView.contentInset.left, y: -scrollView.contentInset.top)
targetContentOffset.memory = offset
}
}
extension HomeViewController : PFLogInViewControllerDelegate, PFSignUpViewControllerDelegate{
func presentLoginViewController()
{
let logInController = PFLogInViewController()
let signupController = PFSignUpViewController()
signupController.delegate = self
logInController.delegate = self
logInController.fields = [PFLogInFields.UsernameAndPassword, PFLogInFields.LogInButton, PFLogInFields.SignUpButton]
logInController.signUpController = signupController
presentViewController(logInController, animated: true, completion: nil)
}
func logInViewController(logInController: PFLogInViewController, didLogInUser user: PFUser)
{
logInController.dismissViewControllerAnimated(true, completion: nil)
}
func signUpViewController(signUpController: PFSignUpViewController, didSignUpUser user: PFUser)
{
signUpController.dismissViewControllerAnimated(true, completion: nil)
}
}
Thanks guys :)

Why is my Swift string variable returning nil?

I am trying to use Parse to create a simple tableview that triggers the URLs of PDF documents that I have uploaded to the Parse Cloud.
In the code below, my variable thePDFFile does output a URL correctly to the console. But when I try to return that variable, it comes up nil and the app crashes.
I am pretty sure that I am not unwrapping an optional correctly, but I can't see where.
The function with the error is named GrabPDF()->String.
import UIKit
import Parse
import Bolts
import AVFoundation
import AVKit
public var AudioPlayer = AVPlayer()
public var SelectedSong = Int()
var theFile:String!
var thePDFFile:String!
class TableViewController: UITableViewController, AVAudioPlayerDelegate {
var iDArray = [String]()
var NameArray = [String]()
var PDFArray = [String]()
var PDFFileArray = [PFObject]()
override func viewDidLoad() {
super.viewDidLoad()
var ObjectIDQuery = PFQuery(className:"Recordings")
ObjectIDQuery.findObjectsInBackgroundWithBlock({
(objectsArray : [AnyObject]?, error: NSError?) -> Void in
var objectIDs = objectsArray as! [PFObject]
for i in 0...objectIDs.count-1{
self.iDArray.append(objectIDs[i].valueForKey("objectId") as! String)
self.NameArray.append(objectIDs[i].valueForKey("RecordingName") as! String)
self.PDFArray.append(objectIDs[i].valueForKey("PDFFileName") as! String)
self.tableView.reloadData()
}
})
}
func grabSong() {
var SongQuery = PFQuery(className:"Recordings")
SongQuery.getObjectInBackgroundWithId(iDArray[SelectedSong], block: {
(object : PFObject?, error : NSError?) -> Void in
if let AudioFileURLTemp = object?.objectForKey("RecordingFile")?.url {
AudioPlayer = AVPlayer(URL: NSURL(string: AudioFileURLTemp!))
AudioPlayer.play()
theFile = AudioFileURLTemp
}
})
}
func grabPDF() -> String {
var PDFQuery = PFQuery(className:"Recordings")
PDFQuery.getObjectInBackgroundWithId(iDArray[SelectedSong], block: {
(object: PFObject?, error : NSError?) -> Void in
if let PDFFileURLTemp = object?.objectForKey("PDFFile")?.url {
println(PDFFileURLTemp)
let thePDFFile = PDFFileURLTemp! as String
println("The value of thePDFFile is \(thePDFFile)")
}
})
return thePDFFile
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return iDArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell
cell.textLabel?.text = NameArray[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
SelectedSong = indexPath.row
grabSong()
grabPDF()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "WebView" {
if let VC2 = segue.destinationViewController as? WebViewController {
if let indexPath = tableView.indexPathForSelectedRow()?.row {
VC2.sentData = theFile
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
You're shadowing thePDFFile with that let. The shadow is popped off the stack when you pass the closing brace and you're returning the instance variable which was not set

How can I add a top margin to my tableview in Xcode?

I'm trying to add an image on the very top of the first cell of a table view. How can i make the table view have a top margin? Right now, the image is just overlapping the tableview. I am trying to just get the table view to come down a little bit. I do not want to make it smaller or something like that. I just want to add a button to the top of the tableview.
//
// usersVC.swift
// CaastRun
//
// Created by Computer on 5/23/15.
// Copyright (c) 2015 Caast. All rights reserved.
//
import UIKit
class usersVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var resultsTable: UITableView!
var resultsNameArray = [String]()
var resultsUserNameArray = [String]()
var resultsImageFiles = [PFFile]()
override func viewDidLoad() {
super.viewDidLoad()
let theWidth = view.frame.size.width
let theHeight = view.frame.size.height
resultsTable.frame = CGRectMake(0, 0, theWidth, theHeight)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
resultsNameArray.removeAll(keepCapacity: false)
resultsUserNameArray.removeAll(keepCapacity: false)
resultsImageFiles.removeAll(keepCapacity: false)
var query = PFUser.query()
query!.whereKey("username", notEqualTo: PFUser.currentUser()!.username!)
query!.findObjectsInBackgroundWithBlock {
(objects:[AnyObject]?, error:NSError?) -> Void in
if error == nil {
for object in objects! {
self.resultsNameArray.append(object.objectForKey("profileName") as! String)
self.resultsImageFiles.append(object.objectForKey("photo") as! PFFile)
self.resultsUserNameArray.append(object.objectForKey("username") as! String)
self.resultsTable.reloadData()
}
}
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return resultsNameArray.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 64
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:usersCell = tableView.dequeueReusableCellWithIdentifier("Cell") as! usersCell
cell.profileLbl.text = self.resultsNameArray[indexPath.row]
cell.usernameLbl.text = self.resultsUserNameArray[indexPath.row]
var query = PFQuery(className: "follow")
query.whereKey("user", equalTo: PFUser.currentUser()!.username!)
query.whereKey("userToFollow", equalTo: cell.usernameLbl.text!)
query.countObjectsInBackgroundWithBlock {
(count:Int32, error:NSError?) -> Void in
if error == nil {
if count == 0 {
cell.followBtn.setTitle("Follow", forState: UIControlState.Normal)
} else {
cell.followBtn.setTitle("Following", forState: UIControlState.Normal)
}
}
}
self.resultsImageFiles[indexPath.row].getDataInBackgroundWithBlock {
(imageData:NSData?, error:NSError?) -> Void in
if error == nil {
let image = UIImage(data: imageData!)
cell.imgView.image = image
}
}
return cell
}
#IBOutlet weak var searchText: UITextField!
#IBAction func searchButton(sender: AnyObject) {
resultsNameArray.removeAll(keepCapacity: false)
resultsUserNameArray.removeAll(keepCapacity: false)
resultsImageFiles.removeAll(keepCapacity: false)
var query = PFUser.query()
query!.whereKey("username", notEqualTo: PFUser.currentUser()!.username!)
query!.whereKey("profileName", containsString: self.searchText.text)
query!.findObjectsInBackgroundWithBlock {
(objects:[AnyObject]?, error:NSError?) -> Void in
if error == nil {
for object in objects! {
self.resultsNameArray.append(object.objectForKey("profileName") as! String)
self.resultsImageFiles.append(object.objectForKey("photo") as! PFFile)
self.resultsUserNameArray.append(object.objectForKey("username") as! String)
self.resultsTable.reloadData()
}
}
}
}
}
I am not sure if I understand your question, if you are trying to have a margin between your table and the view try this:
Swift 3
self.tableView.contentInset = UIEdgeInsets(top: 20,left: 0,bottom: 0,right: 0)
Swift 2
self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0);

swift - adding values between 2 view controllers by prepareforsegue

I have 2 ViewControllers: ViewController1, ViewController2. An "Add" button in ViewController1 will bring up ViewController2. User will then enter in values into ViewController2 which will then be passed back into ViewController1 by prepareforsegue. These values are then append onto the properties of type array in viewcontroller1.
This is being repeated, whereby the user continue pressing the add button to bring up ViewController2 from ViewController1, and then add in new values to be appended onto the properties of array type in ViewController1 via prepareforsegue.
However this is not the case after the first set of values being appended from ViewController2. The second set of values will overwrite the first set of values.
Example.
After the first passed -> force =[1], stiffness[1]
After the second passed -> force=[2], stiffness[2]
I will want this -> force = [1,2], stiffness[1,2]
I want to continue adding until -> force = [1,2,3,4,5], stiffness[1,2,3,4,5]
ViewController1
class ViewController1: UITableViewController, UITableViewDataSource {
var force = [Float]()
var stiffness = [Float] ()
#IBAction func Add(sender: AnyObject) { }
}
ViewController2
class ViewController2: UIViewController {
var forceVar : Float = 0.0
var stiffVar : Float = 0.0
#IBAction func submit(sender: AnyObject) {
self.performSegueWithIdentifier("springSubmit", sender: sender)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if(segue.identifier == "springSubmit") {
var svcSubmitVariables = segue.destinationViewController as ViewController1
svcSubmitVariables.force.append(forceVar)
svcSubmitVariables.stiffness.append(stiffVar)
}
The performSegueWithIdentifier method will always initialize new view controller so in your example view controller that showed ViewController2 is different object from object initialized after submitting data and ofc this newly initialized object will have only initialize values. To achieve what you are looking for you will need to declare a function on your ViewController1 that will append data to your arrays, pass that function to ViewController2 and call it on submit method so your view controllers would look similar like these:
ViewController1
class ViewController1: UITableViewController, UITableViewDataSource {
var force = [Float]()
var stiffness = [Float] ()
override func viewWillAppear(animated: Bool) {
//check if values are updated
println(force)
println(stiffness)
}
#IBAction func Add(sender: AnyObject) {
self.performSegueWithIdentifier("viewController2", sender: sender)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if(segue.identifier == "viewController2") {
var addVariables = segue.destinationViewController as ViewController2
addVariables.submitFunc = appendData
}
}
func appendData(newForce:Float,newStiffness:Force){
force.append(newForce)
stiffness.append(newStiffness)
}
}
ViewController2
class ViewController2: UIViewController {
var forceVar : Float = 0.0
var stiffVar : Float = 0.0
var submitFunc:((newForce:Float,newStiff:Float)->())!
#IBAction func submit(sender: AnyObject) {
submitFunc(forceVar,stiffVar)
self.dismissViewControllerAnimated(false, completion: nil)
}
}
ViewController
import UIKit
class ViewController: UITableViewController, UITableViewDataSource {
var springNumber:NSInteger = 0
var force = [Float]()
var stiffness = [Float] ()
// MARK: UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return springNumber
}
override func tableView(tableView: UITableView,
cellForRowAtIndexPath
indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell")
as UITableViewCell
cell.textLabel!.text = "Spring \(indexPath.row)"
return cell
}
func fwall() -> Float {
for rows in 0..<(springNumber+1) {
force[0] = force[0] + force[rows]
}
force[0] = -(force[0])
return force[0]
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
title = "Springs' Variables"
tableView.registerClass(UITableViewCell.self,
forCellReuseIdentifier: "Cell")
if(springNumber==0) {
force.append(0.0) }
println(force)
println(stiffness)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Adding Values
#IBAction func Add(sender: AnyObject) {
self.performSegueWithIdentifier("addSpring", sender: sender)
}
#IBAction func solve_Pressed(sender: AnyObject) {
self.fwall()
self.performSegueWithIdentifier("Solve", sender: sender)
}
func appendData (newForce: Float, newStiffness:Float, newSpring: NSInteger) {
force.append(newForce)
stiffness.append(newStiffness)
springNumber = newSpring
println(springNumber)
println(force)
println(stiffness)
}
override func prepareForSegue ( segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "addSpring") {
var addVariables = segue.destinationViewController as SpringTableViewControllerInsertVariables
addVariables.submitFunc = appendData
}
if (segue.identifier == "Solve") {
var svcViewController2 = segue.destinationViewController as ViewController2
svcViewController2.forceView2 = self.force
svcViewController2.stiffView2 = self.stiffness
svcViewController2.springNumView2 = self.springNumber
}
if (segue.identifier == "showDetail") {
}
}
}
Code for springTableViewControllerInsertVariables
import UIKit
class SpringTableViewControllerInsertVariables: UIViewController {
var forceVar : Float = 0.0
var stiffVar : Float = 0.0
var springNum : NSInteger = 0
var submitFunc: ((newForce:Float,newStiff:Float,newSpring:NSInteger)->())!
#IBOutlet weak var image: UIImageView!
var imageArray :[UIImage] = [UIImage(named: "springAtWall.jpg")!, UIImage(named:"spring.jpg")!]
override func viewDidLoad() {
if(springNum == 0) {image.image = imageArray[0] }
else {image.image = imageArray[1] }
}
#IBOutlet weak var force: UILabel!
#IBOutlet weak var forceEntered: UITextField!
#IBOutlet weak var stiffness: UILabel!
#IBOutlet weak var stiffnessEntered: UITextField!
#IBAction func checkboxed(sender: AnyObject) {
//when checkedboxed is checked here.
//1)UIImage is changed
//2)calculate2 function is used for calculate1
}
#IBAction func submit(sender: AnyObject) {
//might not work because springNum will be initialise to zero when this viewcontroller starts...
forceVar = (forceEntered.text as NSString).floatValue
stiffVar = (stiffnessEntered.text as NSString).floatValue
springNum = springNum + 1
submitFunc(newForce: forceVar ,newStiff: stiffVar, newSpring: springNum)
self.dismissViewControllerAnimated(false, completion: nil)
}
}

Resources