picker self given a Thread 1 ERROR - swift2

I'm new in coding and i'm loving it, i'm trying to use a picker but i'm getting this error. I did just the same i did in my other project but now it's not working...
May this being happening because i have more than 1 view controller?
her is my code, the error is in the picture i've uploaded
//
// ViewController.swift
// Lucky Numbershhh
//
// Created by Rafael Esper on 5/19/16.
// Copyright © 2016 mudo25. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
// Escolhe os tipos de números
#IBOutlet weak var picker: UIPickerView!
var tipoNumeros = ["Números Aleatórios","Números mais sorteados","Números Menos sorteados"]
var arrayMegaSena = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60]
var arrayMegaSenaMais = [4,5,10,13,17,23,24,28,29,33,41,42,49,51,52,53,54]
var arrayMegaMenos = [3,9,14,15,19,21,22,25,26,39,40,48,55,57]
var arrayQuina = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80]
var arrayQuinaSenaMais = [1,2,3,4,5,6,7,8,9,10,11,12,13,14]
var arrayQuinaMenos = [69,70,71,72,73,74,75,76,77,78,79,80]
var resultado = []
var quantosNumeros = ("5")
var tipoJogo = ("0")
var tipoNumerosEscolhidos = ("Números Aleatórios")
#IBOutlet weak var LabelQuantosNumeros: UILabel!
#IBOutlet weak var LabelResultado: UILabel!
// Escolhe Mega ou Quina
#IBAction func BotaoMegaOuQuina(sender: UISegmentedControl) {tipoJogo = String(sender.selectedSegmentIndex)
tipoJogo = String(sender.selectedSegmentIndex)
}
#IBOutlet weak var ResultadoMegaOuQuina: UISegmentedControl!
// Escolhe Quantos números
#IBAction func BotaoQuantosNumeros(sender: AnyObject) {
LabelQuantosNumeros.text = String(Int(ResultadoQuantosNumeros.value))
quantosNumeros = String(Int(ResultadoQuantosNumeros.value))
}
#IBOutlet weak var ResultadoQuantosNumeros: UIStepper!
// Sorteio dos números
#IBAction func GeraNumeros(sender: AnyObject) {
}
override func viewDidLoad() {
super.viewDidLoad()
self.picker.delegate = self
self.picker.dataSource = self
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return tipoNumeros.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return tipoNumeros[row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
tipoNumerosEscolhidos = String(tipoNumeros[row])
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

Just add UINavigationControllerDelegate like this:
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource,UINavigationControllerDelegate {
}

Related

swift 4- Save the last data of a text field in a label so that they are displayed when the app is restarted

I have a problem, I want to create a small app in which data in a formula can be charged.
Currently the data from three ViewControllers and one PickerViewController will be given back to the first ViewController.
That works very well too.
Now I want that the data at the start not on "nil" set but have a certain value.
Thereafter, the data entered last should reappear when the app is restarted.
I would like to apologize for my english, it is not my preferred language ...
Here is a part of my code how I wrote it
Main ViewController:
import UIKit
class RecivingViewController: UIViewController, SendDataBack, SendDataBack2, SendDataBack3, SendDataBack4 {
#IBOutlet weak var recivingData: UILabel!
#IBOutlet weak var recivingData2: UILabel!
#IBOutlet weak var recivingData3: UILabel!
#IBOutlet weak var recivingData4: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func userData(data: String) {
recivingData.text = data
}
func userData2(data: String) {
recivingData2.text = data
}
func userData3(data: String) {
recivingData3.text = data
}
func PickerData(data: String){
recivingData4.text = data
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "view1" {
let SendingVC: SendingViewController = segue.destination as! SendingViewController
SendingVC.delegate = self
}
if segue.identifier == "view2" {
let SendingVC2: Sending2ViewController = segue.destination as! Sending2ViewController
SendingVC2.delegate = self
}
if segue.identifier == "view3" {
let SendingVC3: Sending3ViewController = segue.destination as! Sending3ViewController
SendingVC3.delegate = self
}
if segue.identifier == "picker" {
let SendingVC4: PickerViewController = segue.destination as! PickerViewController
SendingVC4.delegate = self
}
}
}
one of the other ViewControllers:
import UIKit
protocol SendDataBack {
func userData(data: String)
}
class SendingViewController: UIViewController {
#IBOutlet weak var DataTxt: UITextField!
var delegate: SendDataBack? = nil
#IBAction func done(_ sender: Any) {
if delegate != nil {
if DataTxt.text != nil {
let data = DataTxt.text
delegate?.userData(data: data!)
dismiss(animated: true, completion: nil)
}
}
}
In order to see data after app is restarted you should use user defaults.
For saving data
UserDefaults.standard.set(newValue, forKey: "data")
For loading data in your view controller, if it's first load, when data is nil
UserDefaults.standard.string(forKey: "data")

How to calculate string in text field by Xcode 8.3.3

I want a solution in my problem.
I have text field in Xcode and I wanna Xcode calculate string thats user input as:
var x = 1
var y = 2
like this
I wanna if the user input xy inside text field, the Xcode calculate like: 1+2
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet var label1: UILabel!
#IBOutlet var label2: UILabel!
#IBOutlet var label3: UILabel!
#IBOutlet var label4: UILabel!
#IBOutlet var tex1: UITextField!
#IBOutlet var tex2: UITextField!
override function viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tex1.delegate = self
tex2.delegate = self
}
override function didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
function textFieldShouldReturn(_ textField: UITextField) -> Bool{
tex1.resignFirstResponder()
tex2.resignFirstResponder()
return true
}
#IBAction function close(_ sender: UIButton) {
tex1.resignFirstResponder()
tex2.resignFirstResponder()
}
#IBAction function pushAction(_ sender: UIButton) {
label4.text = String(Int(tex1.text)+Int(tex2.text))
}
}
var temp = 0
var prevCount = -1
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
var txtAfterUpdate:NSString = textField.text! as NSString
txtAfterUpdate = txtAfterUpdate.replacingCharacters(in: range, with: string).trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) as NSString
let newString:String! = String(txtAfterUpdate)
if(prevCount > newString.characters.count - 1){
if(newString.characters.count - 1 != -1){
self.enterAmount = self.enterAmount - Double(textField.text![(textField.text?.characters.count)! - 1])!
}else{
self.enterAmount = 0
}
}else{
self.enterAmount = Double(newString[newString.characters.count - 1])! + self.enterAmount
}
print("YOUR TOTAL \(self.enterAmount)")
prevCount = newString.characters.count - 1
return true
}
extension String{
subscript(i: Int) -> String {
guard i >= 0 && i < characters.count else { return "" }
return String(self[index(startIndex, offsetBy: i)])
}
subscript(range: Range<Int>) -> String {
let lowerIndex = index(startIndex, offsetBy: max(0,range.lowerBound), limitedBy: endIndex) ?? endIndex
return substring(with: lowerIndex..<(index(lowerIndex, offsetBy: range.upperBound - range.lowerBound, limitedBy: endIndex) ?? endIndex))
}
subscript(range: ClosedRange<Int>) -> String {
let lowerIndex = index(startIndex, offsetBy: max(0,range.lowerBound), limitedBy: endIndex) ?? endIndex
return substring(with: lowerIndex..<(index(lowerIndex, offsetBy: range.upperBound - range.lowerBound + 1, limitedBy: endIndex) ?? endIndex))
}
}
you can use like this
label4.text = "\(((tex1.text?.characters.count)! + (tex2.text?.characters.count)!))"

Optional() in my text view

For one of my static labels on my main story board, it prints out "Optional("United States"). However, I would like it to print out "United States". So my question is, how do I get rid of the "Optional" part? I've already tried doing:
if let p = placemarks!.first{
self.addressLabel.text = "\(p.country)"
}
I think the exclamation mark is supposed to "unwrap" some value right? However, even if I do p = placemarks!.first, it prints out "Optional("United States").
Below is the rest of my code just in case you would like some context:
//
// ViewController.swift
// Map Demo Rob 2
//
// Created by Jae Hyun Kim on 8/17/15.
// Copyright © 2015 Jae Hyun Kim. All rights reserved.
//
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
#IBOutlet weak var latitudeLabel: UILabel!
#IBOutlet weak var longitudeLabel: UILabel!
#IBOutlet weak var courseLabel: UILabel!
#IBOutlet weak var speedLabel: UILabel!
#IBOutlet weak var altitudeLabel: UILabel!
#IBOutlet weak var addressLabel: UILabel!
var manager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
// 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.
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print(locations)
let userLocation: CLLocation = locations[0]
self.latitudeLabel.text = "\(userLocation.coordinate.latitude)"
self.longitudeLabel.text = "\(userLocation.coordinate.longitude)"
self.courseLabel.text = "\(userLocation.course)"
self.speedLabel.text = "\(userLocation.speed)"
self.altitudeLabel.text = "\(userLocation.altitude)"
CLGeocoder().reverseGeocodeLocation(userLocation, completionHandler: {(placemarks, error) -> Void in
print(userLocation)
if error != nil {
print(error)
return
}
else {
if let p = placemarks?.first{
self.addressLabel.text = "\(p.country)"
}
}
})
}
}
In
if let p = placemarks!.first{
self.addressLabel.text = "\(p.country)"
}
p.country is an Optional<String>. You need to unwrap that aswell in order to output only it's content (if it exists).
if let country = placemarks?.first?.country {
self.addressLabel.text = country
}

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

Programmatically switching views swift

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

Resources