How to resign keyboard in iOS - ios

I have made a small program which I use to count the money in the safe at work, but after updating my iPhone, it didn't work anymore.
After a lot of reading and so on I fixed everything, but I haven't found a new way to resign the keyboard.
Before the update I used this:
#IBAction func resignKeyboard(_sender: AnyObject) {
_sender.resignFirstResponder()
}
This doesn't work anymore so I would love a new way of doing it. I have searched quite a bit for a solution, but I haven't understood any of the solutions I have found. So please simplify your answers as a lot as possible.
This is everything from the "ViewController.Swift" from my program:
//
// ViewController.swift
// Pengeskabstæller
//
// Created by Alex on 09/07/2016.
// Copyright © 2016 Alex. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var In50B: UITextField!
#IBOutlet weak var In50L: UITextField!
#IBOutlet weak var In20B: UITextField!
#IBOutlet weak var In20L: UITextField!
#IBOutlet weak var In10B: UITextField!
#IBOutlet weak var In10L: UITextField!
#IBOutlet weak var In5B: UITextField!
#IBOutlet weak var In5L: UITextField!
#IBOutlet weak var In2B: UITextField!
#IBOutlet weak var In2L: UITextField!
#IBOutlet weak var In1B: UITextField!
#IBOutlet weak var In1L: UITextField!
#IBOutlet weak var In05B: UITextField!
#IBOutlet weak var In05L: UITextField!
#IBOutlet weak var Ialt: UILabel!
#IBAction func resignKeyboard(_sender: AnyObject) {
_sender.resignFirstResponder()
}
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 Knap(sender: AnyObject) {
//Hvad knappen gør
//Ganger input ved værdi af bundt eller løse
var x50B: Int = Int(In50B.text!)!
x50B = x50B*5000
var x50L:Int = Int(In50L.text!)!
x50L = x50L*500
var x20B:Int = Int(In20B.text!)!
x20B = x20B*4000
var x20L:Int = Int(In20L.text!)!
x20L = x20L*400
var x10B:Int = Int(In10B.text!)!
x10B = x10B*2000
var x10L:Int = Int(In10L.text!)!
x10L = x10L*200
var x5B:Int = Int(In5B.text!)!
x5B = x5B*1000
var x5L:Int = Int(In5L.text!)!
x5L = x5L*200
var x2B:Int = Int(In2B.text!)!
x2B = x2B*500
var x2L:Int = Int(In2L.text!)!
x2L = x2L*50
var x1B:Int = Int(In1B.text!)!
x1B = x1B*500
var x1L:Int = Int(In1L.text!)!
x1L = x1L*50
var x05B:Int = Int(In05B.text!)!
x05B = x05B*200
var x05L:Int = Int(In05L.text!)!
x05L = x05L*20
//Lægger det hele sammen
let penge1 = (x50B + x50L + x20B)
let penge2 = (x20L + x10B + x10L)
let penge3 = (x5B + x5L + x2B + x2L)
let penge4 = (x1B + x1L + x05B + x05L)
let penge99 = String(penge1+penge2+penge3+penge4)
//Printer ialt
Ialt.text = penge99
}
}

I think this is a better way to do it, instead of adding an outlet.
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
Hope it helps!

Assuming all textFields are subviews of view, you can use endEditing method like this:
#IBAction func resignKeyboard() {
view.endEditing(true)
}

Try to change the sender to UITextField instead of AnyObject and then you can do sender.resignFirstResponder()

Related

Why am I not able to access global variables?

I am new both to coding and to Xcode and am working on my first iOS app - so please forgive me if the answer to my question is obvious to experienced developers.
My app works but the design looks very "old fashioned" due to the buttons I have on each View Controller. I would prefer to use a more modern navigation system using Navigation Bars with Navigation buttons at the top of each screen. However, when I use this method of navigation the global variables entered on my first View Controller cannot be accessed on my final View Controller. I have double checked my Swift code files for each View Controller which, as explained, works fine if I have UIButtons instead of the Navbar.
The only difference I can see is that the Xcode 11 Navbar system uses the "Show" (Push) method of segues between View Controllers whereas my storyboard buttons use modal presentation.
I would be grateful if someone can steer me in the right direction - thanks!
The code showing the global variables from the first view controller is:
\\
import UIKit
var name = ""
var lastname = ""
var address = ""
var city = ""
var zip = ""
var email = ""
var phone = ""
var dateofbirth = ""
class ViewController1: UIViewController {
#IBOutlet weak var outlet: UITextField!
#IBOutlet weak var outlet2: UITextField!
#IBOutlet weak var outlet6: UITextField!
#IBOutlet weak var outlet3: UITextField!
#IBOutlet weak var outlet4: UITextField!
#IBOutlet weak var outlet5: UITextField!
#IBOutlet weak var outlet8: UITextField!
#IBOutlet weak var outlet7: UITextField!
#IBAction func submit(_ sender: Any) {
// Code for First Name
if (outlet.text != "")
{
name = outlet.text!
}
// Code for Last Name
if (outlet2.text != "")
{
lastname = outlet2.text!
}
// Code for Address
if (outlet3.text != "")
{
address = outlet3.text!
}
// Code for city
if (outlet4.text != "")
{
city = outlet4.text!
}
// Code for Zip
if (outlet5.text != "")
{
zip = outlet5.text!
}
// Code for Email
if (outlet6.text != "")
{
email = outlet6.text!
}
// Code for Phone
if (outlet7.text != "")
{
phone = outlet7.text!
}
// Code for Date of Birth
if (outlet8.text != "")
{
dateofbirth = outlet8.text!
}
// Dismissal of Keyboard
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
super.touchesBegan(touches, with: event)
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
\\\\
The code for the final View Controller is:
\\\\
import UIKit
class ReportViewController: UIViewController {
//Client ID Label Outlets
#IBOutlet weak var Label: UILabel!
#IBOutlet weak var Label2: UILabel!
#IBOutlet weak var Label3: UILabel!
#IBOutlet weak var Label4: UILabel!
#IBOutlet weak var Label5: UILabel!
#IBOutlet weak var Label6: UILabel!
#IBOutlet weak var Label7: UILabel!
#IBOutlet weak var Label8: UILabel!
// Return function
#IBAction func unwindToReportVC (_sender:UIStoryboardSegue){
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated:Bool){
// Client ID Labels text using declared global variables
Label.text = name
Label2.text = lastname
Label3.text = address
Label4.text = city
Label5.text = zip
Label6.text = email
Label7.text = phone
Label8.text = dateofbirth
}
}

Cannot use instance member 'userCard1' within property initializer; property initializers run before 'self' is available error [duplicate]

This question already has answers here:
How to initialize properties that depend on each other
(4 answers)
Closed 2 years ago.
Trying to make a simple Blackjack app to get comfortable with using Xcode. I've never coded in Swift before and have a little experience in C++. Having an error I don't know how to fix. I'm having trouble applying other answers to similar questions to my situation.
I'm not totally sure what's causing the problem, let alone how to fix it :)
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
var balance = 500
let suits = ["h","d","c","s"]
//user card declarations
#IBOutlet weak var userCard1: UIImageView!
#IBOutlet weak var userCard2: UIImageView!
#IBOutlet weak var userCard3: UIImageView!
#IBOutlet weak var userCard4: UIImageView!
#IBOutlet weak var userCard5: UIImageView!
#IBOutlet weak var userCard6: UIImageView!
#IBOutlet weak var userCard7: UIImageView!
#IBOutlet weak var userCard8: UIImageView!
#IBOutlet weak var userCard9: UIImageView!
#IBOutlet weak var userCard10: UIImageView!
//dealer card declarations
#IBOutlet weak var dealerCard1: UIImageView!
#IBOutlet weak var dealerCard2: UIImageView!
#IBOutlet weak var dealerCard3: UIImageView!
#IBOutlet weak var dealerCard4: UIImageView!
#IBOutlet weak var dealerCard5: UIImageView!
var win = false
var bet = 0
//bet label
#IBOutlet weak var betLabel: UILabel!
//bet slider
#IBAction func betSlider(_ sender: UISlider) {
betLabel.text = String(Int(sender.value))
}
#IBOutlet weak var betSliderValue: UISlider!
var userCardSlot = 3
var dealerCardSlot = 3
var userTotal = 0
var dealerTotal = 0
//user cards displayed
var userCardArray = [userCard1, userCard2, userCard3, userCard4, userCard5, userCard6, userCard7, userCard8, userCard9, userCard10]
//dealer cards displayed
var dealerCardArray = [dealerCard1, dealerCard2, dealerCard3, dealerCard4, dealerCard5]
//hit button
#IBAction func hitTapped(_ sender: Any) {
var cardNum = Int.random(in: 2...14)
var cardSuit = Int(arc4random()) % 4
userCardArray[userCardSlot].image = UIImage(named: "\(cardSuit)card\(cardNum)")
}
//stand button
#IBAction func standTapped(_ sender: Any) {
for userTotal in userCardArray.reversed() {
userTotal += cardNum
}
for dealerTotal in dealerCardArray {
dealerTotal += cardNum
}
while dealerTotal < 17 {
dealerCardSlot += 1
dealerCardArray[dealerCardSlot].image = UIImage(named: "\(cardSuit)card\(cardNum)")
}
if dealerTotal <= userTotal {
win = true
} else {
win = false
}
}
#IBAction func newRoundTapped(_ sender: Any) {
bet = Int(betSliderValue.value)
userCardArray[0].image = UIImage(named: "\(cardSuit)card\(cardNum)")
userCardArray[1].image = UIImage(named: "\(cardSuit)card\(cardNum)")
dealerCardArray[0].image = UIImage(named: "\(cardSuit)card\(cardNum)")
dealerCardArray[0].image = UIImage(named: "Red_back.jpg")
//prompt for hit or stand
if win == true {
balance += (bet * 2)
} else {
balance -= bet
}
}
}
Any help's appreciated!
You generally cannot use one property to initialize another outside of init, because when you do:
var b = a + 1
the compiler implicitly does:
var b = self.a + 1
but self is not yet available; it's only available during the init.
The only exception is a lazy property initializer:
lazy var b: Int = self.a + 1
In your case, you can move the initialization into init:
var userCardArray: [UIImageView]
init() {
self.userCardArray = [userCard1, userCard2, ... ]
}

Pass Data from Class to Class

So I'm trying to program an "Mad Lib" themed app for a class I'm in but I keep getting a
EXC_BAD_INSTRUCTION
error when I hit the submit button. The other students in the class couldn't figure it out either. Please help me!
Here is my firstViewController.swift:
import UIKit
class ViewController: UIViewController
{
#IBOutlet weak var firstTextField: UITextField! //adjective
#IBOutlet weak var secondTextField: UITextField! //male name
#IBOutlet weak var thirdTextField: UITextField! //verb
#IBOutlet weak var fourthTextField: UITextField! //female name
#IBOutlet weak var fifthTextField: UITextField! //adjective
#IBOutlet weak var sixthTextField: UITextField! //athlete
#IBOutlet weak var seventhTextField: UITextField! //food
#IBOutlet weak var eighthTextField: UITextField! //restaurant name
var userInfo = myCustomClass()
override func viewDidLoad()
{
super.viewDidLoad()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
userInfo.adjectiveOne = firstTextField.text!
userInfo.maleName = secondTextField.text!
userInfo.verb = thirdTextField.text!
userInfo.femaleName = fourthTextField.text!
userInfo.adjectiveTwo = fifthTextField.text!
userInfo.athlete = sixthTextField.text!
userInfo.food = seventhTextField.text!
userInfo.restaurantName = eighthTextField.text!
let nextView = segue.destination as! secondViewController
nextView.passedObject = userInfo
}
}
Here is my secondViewController.swift:
import UIKit
class secondViewController: UIViewController
{
var passedObject = myCustomClass()
#IBOutlet weak var myFinishedProduct: UILabel!
override func viewDidLoad()
{
super.viewDidLoad()
myFinishedProduct.text = "There was once a \(passedObject.adjectiveOne) man /n \(passedObject.maleName). One day while he was \(passedObject.verb) he saw /n \(passedObject.femaleName), a rather \(passedObject.adjectiveTwo) woman. /n She was also a \(passedObject.athlete), and a very good /n one too. The two went to lunch together at \(passedObject.restaurantName) /n and ate some \(passedObject.food). After /n that they never crossed paths again."
}
}
Finally here is my NSOBject called "myCustomClass.swift":
import UIKit
class myCustomClass: NSObject
{
var adjectiveOne = ""
var maleName = ""
var verb = ""
var femaleName = ""
var adjectiveTwo = ""
var athlete = ""
var food = ""
var restaurantName = ""
}
Basically, `whatever the user enters into the eight text fields will be stored in myCustomClass when the submit button is pressed. From there, in the secondViewController it will put the eight inputs into the story and display it on a label.
Any help is appreciated, thank you!
Edit: The "Submit Button" is connected to the secondViewController on my storybook with the purpose of "show".
First View Controller
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var txtmobile: UITextField!
#IBOutlet weak var txtlname: UITextField!
#IBOutlet weak var txtfname: UITextField!
var ArrayStudent:[PassData] = []
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 btnclick(_ sender: UIButton)
{
let objdata = PassData(fname: txtfname.text!, lname: txtlname.text!, mobile: txtmobile.text!)
ArrayStudent.append(objdata)
passdata()
}
func passdata()
{
let objstory = storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
objstory.Arradata1 = ArrayStudent
_ = self.navigationController?.pushViewController(objstory, animated: true)
}
}
Second View Controller
import UIKit
class SecondViewController: UIViewController {
#IBOutlet weak var lblmobile: UILabel!
#IBOutlet weak var lbllastname: UILabel!
#IBOutlet weak var lblname: UILabel!
var Arradata1:[PassData ] = []
override func viewDidLoad() {
super.viewDidLoad()
lblname.text = Arradata1.first?.StrFirstName
lbllastname.text = Arradata1.first?.StrLastName
lblmobile.text = Arradata1.first?.StrMobile
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
NSObject Class
import UIKit
class PassData: NSObject
{
var StrFirstName:String!
var StrLastName:String!
var StrMobile:String!
init(fname:String , lname:String , mobile:String)
{
StrMobile = mobile
StrFirstName = fname
StrLastName = lname
}
}

My app is simple app is crashing

I have made a small program which I use to count the money in the safe at work. But after updating my iPhone it crashes. I have tried a lot but can't find a solution.
The crash happens when I press the button which activates the following function:
#IBAction func Knap(sender: AnyObject) {}
I'm very new to coding so please keep the answers as simple as possible :)
My app is as follows:
//
// ViewController.swift
// Pengeskabstæller
//
// Created by Alex on 09/07/2016.
// Copyright © 2016 Alex. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var In50B: UITextField!
#IBOutlet weak var In50L: UITextField!
#IBOutlet weak var In20B: UITextField!
#IBOutlet weak var In20L: UITextField!
#IBOutlet weak var In10B: UITextField!
#IBOutlet weak var In10L: UITextField!
#IBOutlet weak var In5B: UITextField!
#IBOutlet weak var In5L: UITextField!
#IBOutlet weak var In2B: UITextField!
#IBOutlet weak var In2L: UITextField!
#IBOutlet weak var In1B: UITextField!
#IBOutlet weak var In1L: UITextField!
#IBOutlet weak var In05B: UITextField!
#IBOutlet weak var In05L: UITextField!
#IBOutlet weak var Ialt: UILabel!
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 touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
#IBAction func Knap(sender: AnyObject) {
//Hvad knappen gør
//Ganger input ved værdi af bundt eller løse
var x50B: Int = Int(In50B.text!)!
x50B = x50B*5000
var x50L:Int = Int(In50L.text!)!
x50L = x50L*500
var x20B:Int = Int(In20B.text!)!
x20B = x20B*4000
var x20L:Int = Int(In20L.text!)!
x20L = x20L*400
var x10B:Int = Int(In10B.text!)!
x10B = x10B*2000
var x10L:Int = Int(In10L.text!)!
x10L = x10L*200
var x5B:Int = Int(In5B.text!)!
x5B = x5B*1000
var x5L:Int = Int(In5L.text!)!
x5L = x5L*200
var x2B:Int = Int(In2B.text!)!
x2B = x2B*500
var x2L:Int = Int(In2L.text!)!
x2L = x2L*50
var x1B:Int = Int(In1B.text!)!
x1B = x1B*500
var x1L:Int = Int(In1L.text!)!
x1L = x1L*50
var x05B:Int = Int(In05B.text!)!
x05B = x05B*200
var x05L:Int = Int(In05L.text!)!
x05L = x05L*20
//Lægger det hele sammen
let penge1 = (x50B + x50L + x20B)
let penge2 = (x20L + x10B + x10L)
let penge3 = (x5B + x5L + x2B + x2L)
let penge4 = (x1B + x1L + x05B + x05L)
let penge99 = String(penge1+penge2+penge3+penge4)
//Printer ialt
Ialt.text = penge99
}
}
The crash notes is:
2016-10-30 01:13:57.687826 Pengeskabstæller[879:222437] -[Pengeskabstæller.ViewController Knap:]: unrecognized selector sent to instance 0x13fe0aac0
2016-10-30 01:13:57.688704 Pengeskabstæller[879:222437] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Pengeskabstæller.ViewController Knap:]: unrecognized selector sent to instance 0x13fe0aac0'
*** First throw call stack:
(0x1858641c0 0x18429c55c 0x18586b278 0x185868278 0x18576259c 0x18b6e19a0 0x18b6e1920 0x18b6cbdd0 0x18b6e120c 0x18b6e0d34 0x18b6dbf7c 0x18b6aca44 0x18be99ea8 0x18be93910 0x185812278 0x185811bc0 0x18580f7c0 0x18573e048 0x1871c1198 0x18b717818 0x18b712550 0x1000e9368 0x1847205b8)
libc++abi.dylib: terminating with uncaught exception of type NSException
Replace this:
#IBAction func Knap(sender: AnyObject)
with this
#IBAction func Knap(_ sender: AnyObject)
Since Swift 3 you need add an underscore before external parameter name if you want it to be omitted. Most probably the reason for your issue is that you had added IBActions before you have migrated to Swift 3

Thread 1: SIGABRT

This is my first question (and program in Xcode to be honest) so apologies if I break any formatting rules, etc!
I am having an issue when creating an area calculator (to be used at a later date in a quote calculator) and having looked at every SIGABRT thread I could find, but I have been unable to resolve it.
import UIKit
class ViewController: UIViewController{
#IBOutlet weak var forename: UITextField!
#IBOutlet weak var surname: UITextField!
#IBOutlet weak var email: UITextField!
#IBOutlet weak var widthInput: UITextField!
#IBOutlet weak var lengthInput: UITextField!
#IBOutlet weak var areaOutput: UILabel!
#IBOutlet weak var perimeterOutput: UILabel!
#IBOutlet weak var results: UILabel!
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 calculate(sender: AnyObject) {
let width = NSString(string: widthInput.text).doubleValue
let length = NSString(string: lengthInput.text).doubleValue
// The calculation used to work out the area of a room
var area = width * length
areaOutput.text = "\(area)"
// The calculation used to work out the perimeter of a room
var perimeter = 2 * (length + width)
perimeterOutput.text = "\(perimeter)"
}
Any help would be appreciated.
Thanks,
Marc

Resources