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

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.

Related

Firebase Firestore collectionGroup() query method not recognized - swift

I am trying to build out a collection group query.
It is for the iOS swift environment. I have the latest Xcode, Swift, firebase, and firestore all running on my machine.
When I try to create a collection group query, the compiler does not offer the collectionGroup() method and throws an error as unrecognized when I type it out myself.
Any else running into this?
Help please?
I wonder if I skipped a step in terminal, but I have followed all google provided documentation to the letter.
Thanks in advance.
EDIT: here is the relevant code in my ViewController:
import UIKit
import Firebase
class FindYourAcademyViewController: UIViewController, UITableViewDelegate,
UITableViewDataSource {
#IBOutlet weak var searchStackView: UIStackView!
#IBOutlet weak var nameSearchTextField: UITextField!
#IBOutlet weak var locationSearchTextField: UITextField!
#IBOutlet weak var pleaseFindAcademyLabelOutlet: UILabel!
#IBOutlet weak var searchResultsTableViewOutlet: UITableView!
#IBOutlet weak var nextButtonOutlet: DesignableButton!
var db: Firestore!
override func viewDidLoad() {
super.viewDidLoad()
nameSearchTextField.delegate = self
locationSearchTextField.delegate = self
searchResultsTableViewOutlet.isHidden = true
searchResultsTableViewOutlet.delegate = self
searchResultsTableViewOutlet.dataSource = self
let settings = FirestoreSettings()
Firestore.firestore().settings = settings
db = Firestore.firestore()
}
}
// MARK: - UITextField Delegate methods and Keyboard handling
extension FindYourAcademyViewController: UITextFieldDelegate {
// UITextField Delegate methods
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == nameSearchTextField {
textField.resignFirstResponder()
locationSearchTextField.becomeFirstResponder()
print("Next button tapped")
} else if textField == locationSearchTextField {
textField.resignFirstResponder()
print("Search button tapped")
isSearching = false
// keyboard search button fires off the firestore query and returns the query search results
db.collectionGroup() /* <-- THIS WHERE THE ERROR IS THROWN */
}
return true
}
}
i ran a pod update and the issue was resolved, so lesson learned, be sure to update those pods in addition to installing the desired ones!

Printing UITextField input to console

I am trying to print my input from textfields I have setup to the console before I print them to a label. I've tried string interpolation and various other methods, but I can't seem to get it to print the inputs themselves. I know force unwrapping is frowned upon but I will handle it properly after I get this to work. I've checked other asks extensively but found nothing specific to this in particular
To be clearer, when I press submit I want the text from the textfields to print to the console. Right now what happens is the values only show up at (UITextfield)
class SPProfileViewController: UIViewController {
#IBOutlet weak var typeOfCompany: UITextField!
#IBOutlet weak var firstName: UITextField!
#IBOutlet weak var lastName: UITextField!
#IBOutlet weak var email: UITextField!
#IBOutlet weak var cellPhone: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
typeOfCompany.delegate = self
firstName.delegate = self
lastName.delegate = self
email.delegate = self
cellPhone.delegate = self
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
cellPhone.resignFirstResponder()
}
#IBAction func onSubmit(_ sender: UITextField) {
print(self.typeOfCompany.text!)
print(self.firstName.text!)
print(self.lastName.text!)
print(self.email.text!)
print(self.cellPhone.text!)
}
}
extension SPProfileViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
You are watching variables view, Click on "show the console" icon at bottom right corner to view console area.
If that is not your problem than make sure IBAction onSubmit is connected to storyboard.

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

How to move keyboard up over many textFields inside UiView

I have the following in the ViewController:
a) a long viewScroller ( 1000 Height)
b) This long viewScroller contain a UIView Which is 1000 Height, called it 1stView
c) In this 1st UIView (1000 Height), it contain another UiView ( called it 2ndView)
d) in this 2ndUIView( the size: W300x H290) , it contains 5 textFields.
The problems:
1) How to I move the 5 textFields above the Keyboard when user click any one of the textFields to enter data?
for problem (v1) as below
2) below code for problem (V2).
When click outside ( 2ndView or in 2ndView ) the keyboard wont go away.
3) current codition without any implementation for moving the Keyboard up, the 1st TextField can be seen above the keyboard when user click the textField and need to scroll to see the others. Will AppStore approve this User experience?
class ItemViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var textField1: UITextField!
#IBOutlet weak var textField2: UITextField!
#IBOutlet weak var textField3: UITextField!
#IBOutlet weak var textField4: UITextField!
#IBOutlet weak var textField5: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
textField1.delegate = self
textField2.delegate = self
textField3.delegate = self
textField4.delegate = self
textField5.delegate = self
}
//-(V1)- handle textfield
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func textFieldDidBeginEditing(textField: UItextField) {
}
func textFieldDidEndEditing(textField: UITextField) {
}
//-(V2) Called when the user click on the view (outside the UITextField).
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
}
Thanks

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

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.

Resources