Trouble changing the text on a UIButton in swift [duplicate] - ios

This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 6 years ago.
So, I am very new to XCode and Swift. I am having trouble changing the title text on a UIButton, and I keep getting the error
fatal error: unexpectedly found nil while unwrapping an Optional value
This is my code :
//
// ViewController.swift
// mtgHealthTracker
//
// Created by Reagan McFarland on 5/1/16.
// Copyright © 2016 Reagan McFarland. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
//Mark : Properties
#IBOutlet weak var btnPlayer1Health: UIButton!
#IBOutlet weak var btnPlayer4Health: UIButton!
#IBOutlet weak var btnPlayer3Health: UIButton!
#IBOutlet weak var btnPlayer2Health: UIButton!
#IBOutlet weak var lblCurrWinner: 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.
}
//Mark Actions
#IBAction func btnPlayer1HealthChanged(sender: UIButton, forEvent event: UIEvent) {
btnPlayer1Health.setTitle("Hello World", forState: UIControlState.Normal)
}
#IBAction func btnPlayer2HealthChanged(sender: UIButton, forEvent event: UIEvent) {
}
Help is greatly appreciated! Thanks :)

One or more of your IBOutlet's are not connected within your XIB/Storyboard. Make sure to select your File's Owner and drag your IBOutlet to your XIB/Storyboard element.

Related

'Declaration is only valid at file scope' [duplicate]

This question already has an answer here:
Declaration is only valid at file scope (extension)
(1 answer)
Closed 3 years ago.
I've got a problem with 'Declaration is only valid at file scope' error
I was not modifying any other files than mainstoryboard. Those are all places. (whiteout one 'If != nil') where I was using TextFields. I've been trying nearly everything. Thanks for any help
Code:
class ViewController: UIViewController {
//inputs
#IBOutlet weak var creditValueInput: UITextField! //wartość kredytu, input
#IBOutlet weak var procentageInput: UITextField! //oprocentowanie, input
#IBOutlet weak var yearsInput: UITextField! //ile lat/miesiecy, input
#IBOutlet weak var creditOverallOutput: UILabel!
#IBOutlet weak var creditCalculationOutput: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.creditValueInput.delegate = (self as! UITextFieldDelegate)
self.procentageInput.delegate = (self as! UITextFieldDelegate)
self.yearsInput.delegate = (self as! UITextFieldDelegate)
// Do any additional setup after loading the view.
}
......
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
creditValueInput.resignFirstResponder()
procentageInput.resignFirstResponder()
yearsInput.resignFirstResponder()
.....
extension ViewController: UITextFieldDelegate { !Declaration is only valid at file scope!
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
}
Thanks for any help
It seems like you are writing your extension inside your class.
While extensions are valid at file scope, so you should cut your extension block and paste it outside your class.
Assuming the braces of touchesBegan func are closed correctly.

Handling test changed events in a text field swift

I am building a small iOS application that involves doing certain things when text in a tex fields changes. I have been trying to figure out how I can write certain function to be called when the test changed event occurs but none of those solutions work for me, I believe they are outdated. the most popular solution is this:
textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
and
func textFieldDidChange(_ textField: UITextField) {
}
This solution was posted here: How do I check when a UITextField changes?
However when I try to implement this to my code I get an error saying that value of member UITextView has no member addTarget. I am not sure if the code is wrong or if I'm writing it in the wrong place, I am still learning swift so I'm sorry if there's an obvious error.
Here is my code:
import UIKit
class JournalEntryViewController: UIViewController
{
override func viewDidLoad() {
super.viewDidLoad()
print(RatingSelection.selectedSegmentIndex)
let date = NSDate()
let calendar = NSCalendar.current
let hour = calendar.component(.hour, from: date as Date)
let minutes = calendar.component(.minute, from: date as Date)
print("minutes: ",minutes)
if (minutes == 16)
{
print("got in!!!")
print(TextField.text)
}
func textFieldDidChange(_ textField: UITextField)
{
print("text changed")
}
// This line is the problem, I'm trying to add a text changed event to TextField
TextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBOutlet weak var TodaysDate: UILabel!
#IBOutlet weak var RateDayLabel: UILabel!
#IBOutlet weak var RatingSelection: UISegmentedControl!
#IBOutlet weak var TextField: UITextView!
}
EDIT:
I tried doing this, which is almost a copy of the solution but the statement still doesn't get printed when the text changes in the textview
class JournalEntryViewController: UIViewController, UITextViewDelegate
{
override func viewDidLoad()
{
super.viewDidLoad()
self.textField.delegate = self
func textViewDidChange(_ textView: UITextView)
{
print("text changed!!!")
}
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
#IBOutlet weak var textField: UITextView!
#IBOutlet weak var todaysDate: UILabel!
#IBOutlet weak var rateDayLabel: UILabel!
#IBOutlet weak var ratingSelection: UISegmentedControl!
}
Can anyone please help?
EDIT 2:
I figured out the problem, it wasn't in this code.
Thanks for the help!
Your TextField variable (which should be textField - use a lower case first letter for variables, upper case first letter for classes) is a UITextView, not a UITextField so you are attempting to use an incorrect solution.
For a UITextView you need to implement the appropriate UITextViewDelegate method:
class JournalEntryViewController: UIViewController, UITextViewDelegate
{
override func viewDidLoad()
{
super.viewDidLoad()
self.textField.delegate = self
}
func textViewDidChange(_ textView: UITextView) {
// Do whatever
}
}

Swift Thread 1:EXC_BREAKPOINT error

I'm a newbie to swift and for now it's a pain in the a$$ to code.
I'm trying to make a very simple app where the user enters a number to a textfield
and then when a button is clicked it shows the number + 1 in a label.
I always get this error:
Thread 1:EXC_BREAKPOINT (code=1, subcode=0x1002c11ec)
This is my code:
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var tav: UITextField!
#IBOutlet weak var fogy: UITextField!
#IBOutlet weak var ar: UITextField!
#IBOutlet weak var eredmeny: UILabel!
#IBOutlet weak var szamolasBtn: 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 szamol(_ sender: Any) {
let number = Int(tav.text!)! + 1
eredmeny.text = String(describing: number)
}
}
I ran your code and it works fine if an integer in entered in the textfield. But if you enter any character other than a string then the app crashes because Int(tav.text!)! returns nil and adding 1 to nil. Check for nil first and then add something to it.

fatal error: unexpectedly found nil while unwrapping an Optional value with multiple view controller

I've tried to develop a multi view controller app and I have this error:
fatal error: unexpectedly found nil while unwrapping an Optional value
This is my code:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var lbl_nbVies: UILabel!
#IBOutlet weak var lbl_motCache: UILabel!
#IBOutlet weak var lbl_lettreSaisies: UILabel!
#IBOutlet weak var txt_proposition: UITextField!
// Déclaration des variables
var nbVies: Int = 11
override func viewDidLoad() {
super.viewDidLoad()
// Affichage du nombre de vie dans le label "lbl_nbVies"
lbl_nbVies.text = "Test"
lbl_motCache.text = ""
lbl_lettreSaisies.text = ""
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/* Action lorsque l'on appuie sur le bouton tester */
#IBAction func btn_tester(sender: AnyObject) {
}
/* Action lorsque l'on appuie sur le bouton vider */
#IBAction func btn_vider(sender: AnyObject) {
txt_proposition.text = ""
}
}
Thanks for helping
This can mean that you are trying to call a function of an object which is not initialized.
My guess is that one or several of your outlets are not initialized. So, when your call lbl_nbVies.text, you are calling text function on a nil outlet.
Make sure that your outlets are hooked up properly in the storyboard (you should see a circle near your #IBOutlet).
This means that lbl_nbVies isn't initialised. However if you're creating IBOutlets then they should be set up. One things I've seen people do is create multiple connections to the object (in your course case the label) in interface builder.
Make sure you haven't accidentally set up multiple connections. Select the label in you're nib or storyboard can check the connections inspector.

'IBOutlet' property has non-optional type 'UIButton'

Here's my code:
import UIKit
class ViewController: UIViewController {
#IBOutlet var button: 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.
}
}
It's a simple IBOutlet (straight from the Apple developer docs). It gives me the error "'IBOutlet' property has non-optional type 'UIButton'" and I have no idea how to fix it.
It should be like that (in Beta 3 or before):
#IBOutlet var button: UIButton?
IBOutlets must be optionals so place a ? behind the type.
It can also be-
#IBOutlet var button: UIButton!
or
#IBOutlet var weak button: UIButton! (in case you are not doing view unloading)
if you are using XCODE 6 Beta 4
class SecondViewController: UIViewController {
#IBOutlet weak var name: UILabel! = nil
override func viewDidLoad() {
super.viewDidLoad()
name.text="i m a label"
}
}
This code working fine
But when i replace #IBOutlet weak var name: UILabel? it is not working.

Resources