Swift word processing - swift

I'm making a simple swift application. Right now I have an input text field that takes a user input and outputs it to the output user field when a button is clicked. As shown in the code below:
import UIKit
import Foundation
class ViewController: UIViewController {
#IBOutlet weak var userNameField: UITextField!
#IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
userNameField.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func enterTapped(_ sender: Any) {
textView.text = "\(userNameField.text!)"
}
}
extension ViewController : UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
I wanted to perform some word processing before the text is displayed to the user but, every time I try coding I get a bunch of errors. Where in the code should my word processing code go. When I refer to word processing I'm referring to some string commands such as: split, combine...

It should be here
#IBAction func enterTapped(_ sender: Any) {
let str = userNameField.text!
// do what you want with str
let addComma = str + ","
textView.text = addComma
}

Where in the code should my word processing code go.
you want to do some processing and put the processed text in the out-filed. As this process needs to take place on button action. I understand the processing should go in following method:
#IBAction func enterTapped(_ sender: Any) {
// this is the correct place for processing your string.
let inputStr = userNameField.text!
//Process 'inputStr" as needed.
textView.text = inputStr
}

Related

How do I add a placeholder to my UITextField? (Using Xcode 12)

EDIT: New ErrorCurrently using XCode 12, and I'm trying to add a placeholder. I followed the Swift QuestionBot documentation but it doesn't work (I'm assuming it's because my XCode is much newer). Anyway, appreciate all the help!
EDIT: I added an image of a new error I got.
EDIT 2: Added MyQuestionAnswerer() struct! It's on a different view controller (obvious).
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var responseLabel: UILabel!
#IBOutlet weak var askButton: UIButton!
#IBOutlet weak var questionField: UITextField!
let questionAnswerer = MyQuestionAnswerer()
override func viewDidLoad() {
super.viewDidLoad()
questionField.becomeFirstResponder()
}
func respondToQuestion(_ question: String) {
let answer = questionAnswerer.responseTo(question: question)
displayAnswerTextOnScreen(answer)
questionField.placeholder = "Ask another question..."
questionField.text = nil
askButton.isEnabled = false
}
#IBAction func askButtonTapped(_ sender: AnyObject) {
guard questionField.text != nil else {
return
}
questionField.resignFirstResponder()
}
func displayAnswerTextOnScreen(_ answer: String) {
responseLabel.text = answer
}
}
extension ViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return false
}
func textFieldDidEndEditing(_ textField: UITextField) {
guard let text = textField.text else {
return
}
respondToQuestion(text)
}
#IBAction func editingChanged(_ textField: UITextField) {
guard let text = textField.text else {
askButton.isEnabled = false
return
}
askButton.isEnabled = !text.isEmpty
}
}
struct MyQuestionAnswerer {
func responseTo(question: String) -> String {
let loweredQuestion = question.lowercased()
if loweredQuestion == "What is the current vaccination rate of the Philippines?" {
return "As of August 8, the vaccination rate of the Philippines is 10%!"
} else if loweredQuestion.hasPrefix("Where") {
return "Check the map for nearby vaccination centers."
}
}
The placeholder is not present when the textFiled as it is not set until the respondToQuestion method is called. It should probably be set inside of a view controller life cycle method such as viewDidLoad().
Example:
override func viewDidLoad() {
super.viewDidLoad()
questionField.placeholder = "Ask another question"
questionField.becomeFirstResponder()
}

How can I use a variable defined within a function in the main View Controller in another View Controller?

I'm developing a simple game (my first iOS app!) and am trying to link a variable between two View Controllers. In the first view controller, I have a textfield where the user can type in any number they choose. In the second View Controller, I would like users to be able to generate any number between 1 and the number they entered by pressing a button and be able to keep doing so. However, I am not able to use the "upperBound" variable holding the user-entered value in ViewController2.
I've tried using prepare for segue but it's not working, and I've snooped around stackoverflow and tried a couple of methods without quite knowing what I'm doing to no avail.
(UPDATED) ViewController:
class ViewController: UIViewController, UITextFieldDelegate {
//MARK: Properties
#IBOutlet weak var numberOfPages: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// Handle the text field’s user input through delegate callbacks.
numberOfPages.delegate = self
}
//MARK: UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// Hide the keyboard.
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
//Save number entered and then randomly select a number within bounds
}
//MARK: Actions
var upperBound: Int?
#IBAction func setUpperBound(_ sender: UIButton) {
upperBound = Int(numberOfPages.text!)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
// Create a variable that you want to send
var newUpperBound = Int(upperBound!)
// Create a new variable to store the instance of ViewController2
let destinationVC = segue.destination as! ViewController2
destinationVC.upperBound = newUpperBound
}
}
(UPDATED) ViewController2:
class ViewController2: UIViewController, UITextFieldDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
//Mark: Actions
#IBAction func roller(_ sender: UIButton) {
//Generate random number
let randomNumber = Int.random(in: 0 ..< upperBound)
}
var upperBound: Int?
}
With this code, I'm getting an error on line 34 of ViewController2 that reads "Use of unresolved identifier upperBound". Additionally, there is an issue on line 40 of ViewController that reads "immutable value upperBound was never used". I would expect to be able to generate a random value between 1 and the entered number so that I can keep working and add more features to my app (like printing these random values etc)
ViewController
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var numberOfPages: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
numberOfPages.delegate = self
}
//MARK: UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// Hide the keyboard.
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
//Save number entered and then randomly select a number within bounds
}
//MARK: Actions
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if numberOfPages.text == ""{
print("Please enter number")
return
}
let upperBound: Int? = Int(numberOfPages.text ?? "0")
if upperBound != 0{
if segue.identifier == "mySegue"{
let vc = segue.destination as! ViewController2
vc.upperBound = upperBound
}
}
}
}
ViewController2
import UIKit
class ViewController2: UIViewController {
#IBOutlet weak var lbl_UpperBound: UILabel!
#IBOutlet weak var btn_Generate: UIButton!
#IBOutlet weak var lbl_Random: UILabel!
var upperBound: Int?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
lbl_UpperBound.text = "Upper Bound - \(upperBound ?? 0)"
btn_Generate.addTarget(self, action: #selector(roller), for: .touchUpInside)
lbl_Random.text = ""
}
#objc func roller(_ sender: UIButton) {
//Generate random number
let randomNumber = Int.random(in: 0 ..< (upperBound ?? 1))
lbl_Random.text = "\(randomNumber)"
}
}
Also Don't forget to name the Segue

How to use file.swift into a swift created app(project)?

I have a task to create an app that checks if a String is a palindrome or not. And also I have instructed to create a file and in that file should be a function. But what I can't figure out is how to make a button run that function that is in the file.
func isPalidrone(phrase: String) -> Bool {
let isPalidrone = true
let reversed = String(phrase.reversed())
if reversed == phrase {
return isPalidrone
} else {
return !isPalidrone
}
}
class ViewController: UIViewController {
#IBOutlet weak var Label: UILabel!
#IBOutlet weak var textFieldOutlet: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func buttonPressed(_ sender: Any) {
}
}
Like this:
#IBAction func buttonPressed(_ sender: Any) {
let pal = isPalidrone(phrase: self.textFieldOutlet.text!)
// now pal is true or false and you can decide what else to do ...
// for example:
self.Label.text = pal ? "It is a palindrome" : "It is not a palindrome"
}

textfield not empty show save button in Swift

My save button is hidden with the function saveBtnHidden() in the code below. However, the save button won't reappear when text is typed into the text field. I have tried multiple solutions similar to this. Every time that I type into the text field, the save button just won't show up.
import UIKit
class TableViewController: UITableViewController, UITextFieldDelegate {
#IBOutlet weak var saveBtn: UIButton!
#IBOutlet var nicknameField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
saveBtnHidden()
}
func saveBtnHidden() {
if (nicknameField.text?.isEmpty ?? true) {
// is empty
saveBtn.isHidden = true
} else {
saveBtn.isHidden = false
}
}
#IBAction func saveBtnPressed(_ sender: Any) {
performSegue(withIdentifier: "nextPage", sender: nil)
}
}
You are getting this error because your function saveBtnHidden() is only called once in viewDidLoad(). It does not get called again when the text in your text field changes. To detect when text changes, you will need to add a target to your text field that calls a function when it changes (.editingChanged) like this:
nicknameField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
Then in the textFieldDidChange call your saveBtnHidden() function:
func textFieldDidChange(_ textField: UITextField) {
saveBtnHidden()
}
Code adapted from: How do I check when a UITextField changes?
Use delegate to be notify of any change. Delegates is a key part of iOS development and Apple's framework.
class TableViewController: UITableViewController, UITextFieldDelegate {
#IBOutlet weak var saveBtn: UIButton!
#IBOutlet var nicknameField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
saveBtnHidden()
nicknameField.delegate = self
}
func textFieldDidChange(_ textField: UITextField) {
saveBtnHidden()
}
// More of your source code below...

Converting UITextField to String in Swift

I'm trying to convert a UITextField object to a String so that I can pass it to a function in my model file. But it is printing a blank even after I type in some characters in the name input text field and then click outside of it. Why is nothing stored there?
In view controller file:
#IBOutlet weak var nameInputText: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
nameInputText.delegate = self
let text: String = nameInputText.text!
print(text) //this prints a blank
model.validateName(nametext: text)
}
It should be like below
#IBOutlet weak var usernameInputText : UITextField!
override func viewDidLoad() {
super.viewDidLoad()
usernameInputText.delegate = self
}
func ClickOnButton()
{
let text: String = usernameInputText.text!
print(text) //this prints My text
model.validateName(nametext: text)
}
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String)
-> Bool
{
let text: String = usernameInputText.text!
print(text) //this prints My text
model.validateName(nametext: text)
}
viewDidLoad gets called before your ViewController would be visible to the user, so any text field can only contain text if you have set that text before (in InterfaceBuilder or code). If you want to access user input from that text field, you should either do that in textFieldDidEndEditing or in any other function which you know can only be called after the user interaction happened.
#IBOutlet weak var nameInputText: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
nameInputText.delegate = self
}
extension ViewController: UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
model.validateName(nametext: textField.text)
}
}