I have a textfield in my first View Controller. The input is numbers only, but it's obviously in the form of a string. I've passed it to my second view controller. The code is as follows:
import Foundation
import UIKit
class View3on3Results : UIViewController {
#IBOutlet weak var APResult1: UILabel!
#IBOutlet weak var APResult2: UILabel!
#IBOutlet weak var APResult3: UILabel!
#IBOutlet weak var APResult4: UILabel!
var AP1: String? = String()
var AP2: String? = String()
var AP3: String? = String()
let x:Int? = Int(AP1)
override func viewDidLoad() {
APResult1.text = AP1
APResult2.text = AP2
}
}
I set the Label text to equal the strings I passed just to test if it was working; it is.
I'd now like to cast the strings I just passed to integers. I tried doing that with:
let x:Int? = Int(AP1)
It throws the error: View3on3Results.type does not have a member named 'AP1'. Anyone know what's up with this?
All coded in XCode 7.0 beta 3, using Swift 2.
You can not Initialise your instance that way but you can do that in viewDidLoad method this way:
let x:Int? = AP1?.toInt()
Related
I am a beginner working on an app that will function like a golf scorecard. My first issue has come while attempting to accept user input in a (prototype) series of 9 textFields so the user can type in their scores, and then a textView at the end that is not editable that will show the total for the 9 holes. I am trying to get this to be a running total that updates constantly.
I tried passing the inputs from each textField into an array, and returning the sum of the array to a the textView, but still had issues with the data type from the textField being a string, where as I will only be dealing with integers.
My clunky first pass is as follows -
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var holeOneScore: UITextField!
#IBOutlet weak var holeTwoScore: UITextField!
#IBOutlet weak var holeThreeScore: UITextField!
#IBOutlet weak var holeFourScore: UITextField!
#IBOutlet weak var holeFiveScore: UITextField!
#IBOutlet weak var holeSixScore: UITextField!
#IBOutlet weak var holeSevenScore: UITextField!
#IBOutlet weak var holeEightScore: UITextField!
#IBOutlet weak var holeNineScore: UITextField!
#IBOutlet weak var totalForFrontNine: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
//MARK: Calculate Scores
#IBAction func calculate(_ sender: Any) {
let hole1:Int = Int(holeOneScore.text!)!
let hole2:Int = Int(holeTwoScore.text!)!
let hole3:Int = Int(holeThreeScore.text!)!
let hole4:Int = Int(holeFourScore.text!)!
let hole5:Int = Int(holeFiveScore.text!)!
let hole6:Int = Int(holeSixScore.text!)!
let hole7:Int = Int(holeSevenScore.text!)!
let hole8:Int = Int(holeEightScore.text!)!
let hole9:Int = Int(holeNineScore.text!)!
let totalArray = [hole1, hole2, hole3, hole4, hole5, hole6, hole7, hole8, hole9]
let totalScore = totalArray.reduce(0, +)
totalForFrontNine.text = String(totalScore)
print(totalForFrontNine!)
}
It worked, but barely. Any thoughts to modify this or a complete refresh is fine! I am not tied to anything as i am using this project to just teach me the basics.
Thanks in advance, cheers - glassGarrett
Like #jawadali mentioned, use IBOutletCollection. Here is a tutorial about how to use it.
As for the other issue,
...the data type from the textField being a string, where as I will only be dealing with integers.
A quick solution is to set the keyboardType of your textfield to UIKeyboardTypeNumberPad, or .numberPad in Swift.
textField.keyboardType = .numberPad
Or in storyboard,
I am parsing JSON data to UITableView in which it consists of one image and 5 labels in which one is of type Int and rest are of type String. I have parsed data for type String but when I add Int type to my model class and then write code for displaying cells in cellForItemAt method of UITableViewDelegate, it says cannot assign value of type Int to String.
Here is the screenshot of my app I have tried:
In this, where it says firstappear, there I want to display year like 1970.
Modal Class:
class Hero {
var name:String?
var team:String?
var imageUrl:String?
var realname:String?
var firstappearance:Int?
var publisher:String?
init(name:String?, team:String?, imageUrl:String?, realname:String?, firstappearance:Int?, publisher:String?) {
self.name = name
self.team = team
self.imageUrl = imageUrl
self.realname = realname
self.firstappearance = firstappearance
self.publisher = publisher
}
}
ViewController:
Also when i click the cell in table view i want to display all the contents to another view. I have tried didselectrowat method of table view, but not getting correctly
my source code for didselectroe method as below
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let heroesDetails:HeroesDetailsViewController = self.storyboard?.instantiateViewController(withIdentifier: "HeroesDetailsViewController") as! HeroesDetailsViewController
heroesDetails.heroImage = heroesDetails.detailsImg
heroesDetails.labelName = heroesDetails.detailsName
heroesDetails.labelPublish = heroesDetails.detailsPublisher
heroesDetails.labelAppear = heroesDetails.detailsAppear
heroesDetails.labelTeam = heroesDetails.detailsTeam
heroesDetails.labelRealName = heroesDetails.detailsRealName
self.navigationController?.pushViewController(heroesDetails, animated: true)
}
my another view controller file named as heroesdetailsviewcontroller swift file as below:
import UIKit
class HeroesDetailsViewController: UIViewController {
#IBOutlet weak var detailsImg: UIImageView!
#IBOutlet weak var detailsName: UILabel!
#IBOutlet weak var detailsRealName: UILabel!
#IBOutlet weak var detailsTeam: UILabel!
#IBOutlet weak var detailsAppear: UILabel!
#IBOutlet weak var detailsPublisher: UILabel!
var heroImage: UIImage!
var labelName: String!
var labelTeam: String!
var labelAppear: String!
var labelPublish: String!
var labelRealName: String!
override func viewDidLoad() {
super.viewDidLoad()
detailsImg.image = heroImage
detailsName.text = labelName
detailsRealName.text = labelRealName
detailsTeam.text = labelTeam
detailsAppear.text = labelAppear
detailsPublisher.text = labelPublish
// Do any additional setup after loading the view.
}
}
code screenshot:
I just looked at the API request -> https://simplifiedcoding.net/demos/marvel/
firstappearance is string, update your API model to string instead of int.
class Hero {
var firstappearance:String?
}
It is understandable why you thought it is int, but check the type of the data not the value.
You are assigning Int type to your label which will never accept. So update your following line of code as follow:
cell.labelAppear.text = String(here.firstappearance ?? 0)
Don't type caste again to Int.....
cell.labelAppear.text = String(hero.firstAppearance)
text attribute of UILabel requires string.
Hi I am very new to Swift. I have watched several different videos and tutorials on youtube and I am unable to identify what I am doing wrong.
I am trying to take the data from a check-in view and segue it to the summary view. The code runs, and I am able to move through the app, but the data does not move. Below is the code for the two different swift files. Any insight would be greatly appreciated.
Check-In:
import Foundation
import UIKit
class VieNewCheckIN : UIViewController {
#IBOutlet var SWR: UILabel!
#IBOutlet var ModelNumber: UITextField!
#IBOutlet var SerialNumber: UITextField!
#IBOutlet var Notes: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let viewnewsummary = segue.destination as? ViewNewSummary else { return }
viewnewsummary.NotesValue = Notes.text
viewnewsummary.SerialNumberValue = SerialNumber.text
viewnewsummary.ModelNumberValue = ModelNumber.text
}
}
Summary:
import Foundation
import UIKit
class ViewNewSummary : UIViewController {
#IBOutlet var FirstNameLabel: UILabel!
var FirstNameValue : String!
#IBOutlet var LastNameLabel: UILabel!
var LastNameValue : String!
#IBOutlet var IDLabel: UILabel!
var BaylorIDValue : String!
#IBOutlet var EmailLabel: UILabel!
var BaylorEmailValue : String!
#IBOutlet var PhoneNumberLabel: UILabel!
var PhoneNumberValue : String!
#IBOutlet var ModelNumberLabel: UILabel!
var ModelNumberValue : String!
#IBOutlet var SerialNumberLabel: UILabel!
var SerialNumberValue : String!
#IBOutlet var NotesLabel: UILabel!
var NotesValue : String!
override func viewDidLoad() {
super.viewDidLoad()
FirstNameLabel.text = FirstNameValue
LastNameLabel.text = LastNameValue
BaylorIDLabel.text = BaylorIDValue
BaylorEmailLabel.text = BaylorEmailValue
PhoneNumberLabel.text = PhoneNumberValue
ModelNumberLabel.text = ModelNumberValue
SerialNumberLabel.text = SerialNumberValue
NotesLabel.text = NotesValue
}
}
Verify prepare(for:sender:) is called, e.g. using breakpoints or print/caveman debugging;
verify ViewNewSummary.viewDidLoad() is called, too;
verify prepare is called before viewDidLoad.
My suspicion is that viewDidLoad is called before prepare(for:sender:) is called; that'd make sense since you need an initialized view controller object to prepare the segue with.
So you will want to add viewWillAppear(_:) as a quick fix:
extension ViewNewSummary {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
FirstNameLabel.text = FirstNameValue
LastNameLabel.text = LastNameValue
BaylorIDLabel.text = BaylorIDValue
BaylorEmailLabel.text = BaylorEmailValue
PhoneNumberLabel.text = PhoneNumberValue
ModelNumberLabel.text = ModelNumberValue
SerialNumberLabel.text = SerialNumberValue
NotesLabel.text = NotesValue
}
}
If that doesn't scale well for all cases, you may want to look into property observers, like
var PhoneNumberValue : String! {
didSet {
guard isViewLoaded else { return }
PhoneNumberLabel.text = PhoneNumberValue
}
}
Sorry if this particular problem has been asked about, I followed the answers on other threads but none of them seemed to work, but I just started learning Swift so all of this is pretty new to me.
So, I have a text field in two View Controllers and I want the third View Control to display a result based on the input from the other two controllers when I press a button.
I followed this tutorial and placed the text fields, label and button like I said before.
I placed my code (which you can see below) inside ViewControl.swift.
The problem is that when I attempt to run it I get a "Thread 1 :EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" error in the last two lines.
class ViewController: UIViewController {
var a: String = ""
var b: String = ""
#IBOutlet weak var aTextField: UITextField!
#IBOutlet weak var bTextField: UITextField!
#IBOutlet weak var calculateButton: UIButton!
#IBOutlet weak var resultLabel: UILabel!
#IBAction func calculateButtonPressed(_ sender: UIButton) {
let a = aTextField.text!;
let b = bTextField.text!;
I think that the error is from the data not passing between the views (because before I had everything in the same view and it worked fine), but since I only have one ViewController.swift file I couldn't figure out how to use a Segue.
Do not declare same variables multiple times. Remove let before a & b . You have already declared a & b globally and then tried to redeclare it inside IBAction
class ViewController: UIViewController {
var a: String = ""
var b: String = ""
#IBOutlet weak var aTextField: UITextField!
#IBOutlet weak var bTextField: UITextField!
#IBOutlet weak var calculateButton: UIButton!
#IBOutlet weak var resultLabel: UILabel!
#IBAction func calculateButtonPressed(_ sender: UIButton) {
a = aTextField.text!;
b = bTextField.text!;
Make sure your control outlets are setted properly.
In your two variables a & b are re-declared.Just update your code like below
#IBAction func calculateButtonPressed(_ sender: UIButton) {
self.a = aTextField.text!
self.b = bTextField.text!
}
I get an error saying "EXC_BAD_INSTRUCTION..." in reference to attempting to use redSlider.value to set a value for a property of my "Color" type from another file.(also pasted below)
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
#IBOutlet weak var colorView: UIView!
#IBOutlet weak var redSlider: UISlider!
#IBOutlet weak var greenSlider: UISlider!
#IBOutlet weak var blueSlider: UISlider!
func updateCurrentColor() {
var currentColor = Color(red: redSlider.value, green: greenSlider.value, blue: blueSlider.value)
print("CurrentColor updated!!!")
}
}
And here is my "Color" Type(in another file):
import Foundation
struct Color {
var red = Float()
var green = Float()
var blue = Float()
}
Here is my ViewController
I call updateCurrentColor() from main.swift
import Foundation
import UIKit
ViewController().updateCurrentColor()
ViewController() creates a new view controller object. Since you don't present it on the screen, its outlets never get initialized. That means that the ! on the end of redSlider: UISlider! is a lie.
Even if it didn't crash, updating the color on something you're not putting on the screen doesn't sound very useful.
Use the ViewController you already have instead of creating a new one.