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

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

Related

Change a parameter from a single class to all other classes

I am having a problem that I cant seem to figure it out, I am trying to change the language of the application through sender buttons but I cant change the parameter of the language from the signInViewController to other VC's I am getting an error.
In other classes I created a static let shared = resetPasswordViewController and then call it at the signInViewController to change the labels buttons etc but I am getting a nil error at labels and buttons when its trying to change the language
signInViewController:
class signInViewController: UIViewController {
#IBOutlet weak var welcomeLabelSignIn: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
}
#IBAction func changeLanguageToAlbanian(_ sender: Any) {
localizeSignIn()
resetPasswordViewController.shared.localizeResetPassword()
}
#IBAction func changeLanguageToSerbian(_ sender: Any) {
localizeSignIn1()
resetPasswordViewController.shared.localizeResetPassword()
}
#IBAction func changeLanguageToEnglish(_ sender: Any) {
localizeSignIn2()
resetPasswordViewController.shared.localizeResetPassword()
}
func localizeSignIn() {
welcomeLabelSignIn.text = NSLocalizedString("Welcome!", tableName: nil, bundle: changeLanguage.createBundlePath(lang: "sq" ), value: "", comment: "")
}
resetPasswordViewController:
class resetPasswordViewController: UIViewController {
static let shared = resetPasswordViewController()
#IBOutlet weak var enterEmailLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
localizeResetPassword()
}
func localizeResetPassword() {
enterEmailLabel.text = NSLocalizedString("Welcome!", tableName: nil, bundle: changeLanguage.createBundlePath(lang: "sq" ), value: "", comment: "")
}
Now you see that the (lang: "") is being called as static, I need to make a global one that when the client press the button to change the language it will replace that "" in every other class and then change the language.
I hope I was clear about the problem, for any questions feel free to comment please.
If you want to make a singleton LangHandler you should seperate it into another class so you can make reusable code without typing again
class LangHanlder
class LangHandler {
static let shared = LangHandler()
var lang: String
//Make default lang
private init(){
lang = "sq"
}
func changeLang(_ langChange: String){
lang = langChange
}
}
Have localized extension
extension String {
func localized(_ lang:String) ->String {
let path = Bundle.main.path(forResource: lang, ofType: "lproj")
let bundle = Bundle(path: path!)
return NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "")
}
}
How to use
When you called for the first time you always have default value
signInViewController:
class signInViewController: UIViewController {
#IBOutlet weak var welcomeLabelSignIn: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
}
#IBAction func changeLanguageToAlbanian(_ sender: Any) {
localizeSignIn()
}
#IBAction func changeLanguageToSerbian(_ sender: Any) {
// change localized handler language only
LangHandler.shared.changeLang("sr")
localizeSignIn()
}
#IBAction func changeLanguageToEnglish(_ sender: Any) {
// change localized handler language only
LangHandler.shared.changeLang("en")
localizeSignIn()
}
func localizeSignIn() {
welcomeLabelSignIn.text = "Welcome!".localized(LangHandler.shared.lang)
}
resetPasswordViewController:
class resetPasswordViewController: UIViewController {
#IBOutlet weak var enterEmailLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
localizeResetPassword()
}
func localizeResetPassword() {
// default is sq
enterEmailLabel.text = "Welcome!".localized(LangHandler.shared.lang)
}

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

Two windows are presented when I start my xib only project

I am using Xcode 10.1 two create a simple single window application. The issue is that I see two windows instantiated when I run it instead of the single one I expect. Here is my code
//AppDelegate
import Cocoa
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var mainWindowController: WindowController!
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
print("loading")
let mainWindowController = WindowController()
mainWindowController.showWindow(self)
self.mainWindowController = mainWindowController
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
print("closed")
}
}
//WindowController.swift
import Cocoa
class WindowController: NSWindowController, NSSpeechSynthesizerDelegate {
#IBOutlet weak var textField: NSTextField!
#IBOutlet weak var speakButton: NSButton!
#IBOutlet weak var stopButton: NSButton!
override var windowNibName: String {
return "Window"
}
let speechSynth = NSSpeechSynthesizer()
var isStarted: Bool = false {
didSet {
updateButtons()
}
}
override func windowDidLoad() {
super.windowDidLoad()
viewDidLoad()
}
func viewDidLoad() {
// super.viewDidLoad()
updateButtons()
speechSynth.delegate = self
print("view load")
// Do any additional setup after loading the view.
}
#IBAction func speakIt(sender: NSButton) {
let string = textField.stringValue
if string.isEmpty {
print("String is empty")
}
else {
print(string)
speechSynth.startSpeaking(string)
isStarted = true
}
}
#IBAction func stopIt(sender: NSButton) {
speechSynth.stopSpeaking()
isStarted = false
}
func updateButtons() {
if isStarted {
speakButton.isEnabled = false
stopButton.isEnabled = true
} else {
stopButton.isEnabled = false
speakButton.isEnabled = true
}
}
func speechSynthesizer(_ sender: NSSpeechSynthesizer, didFinishSpeaking finishedSpeaking: Bool) {
isStarted = false
}
}
My Xib has the option checked "Visible at launch". If I uncheck it, I see no window.
Basically, I am attempting a program from the book "Cocoa Programming for OSX". However, the book is obsolete. But I am trying to find my way through new Xcode and Swift. Any help?
Also a point worth noting is that only one window is functional, the second window IBOutlets and IBAction are not connected. So nothing happens in the second window.
I can't figure out why is this happening?

I have a problem with a variable in AppDelegate

I have an error in my code when trying to return a variable that is in the App delegate to a viewController, it returns a null value and therefore does not assign the delegate
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var client: SINClient!
.
.
.
}
class ViewController: UIViewController, SINCallClientDelegate {
#IBOutlet weak var destination: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func client() -> SINClient? {
return (UIApplication.shared.delegate as! AppDelegate).client
}
override func awakeFromNib() {
super.awakeFromNib()
self.client()?.call().delegate = self
}
#IBAction func actionCall(_ sender: UIButton) {
if destination.text != "" && self.client()!.isStarted() {
weak var call = client()!.call().callUserVideo(withId: destination.text)
performSegue(withIdentifier: "callView", sender: call)
}
}
func client(_ client: SINCallClient?, didReceiveIncomingCall call: SINCall?) {
performSegue(withIdentifier: "callView", sender: call)
}
}
Fatal error: Unexpectedly found nil while unwrapping an Optional value

View Controller doesn't find a func member

I'm getting this error:
Value of type 'DiscountVC' has no member 'calculateTotal'. And I have no clue why. Basically, I'm trying to make this calculator:
It should work as soon as you insert any value on the discountTF. Also, I have some pre-discounted buttons that just edit the discount value. The subtotalLabel value comes from another ViewController. For testing purposes, I'm using an initial value of 999.9.
import UIKit
class DiscountVC: UIViewController {
#IBOutlet var numericKeyboardView: UIView!
#IBOutlet var subtotalLabel: UILabel!
#IBOutlet var discountTF: UITextField!
#IBOutlet var totalLabel: UILabel!
var subtotal : Double = 999.9
var discount : Double = 0.0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
addKeyboard(view: numericKeyboardView)
subtotal = 999.9
discount = 0.0
discountTF.addTarget(self, action: #selector(self.calculateTotal(_:)), for: UIControl.Event.editingChanged)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
func calculateTotal() {
let totalDouble = Double(subtotal) - Double(discountTF.text!)!
totalLabel.text = String(totalDouble)
}
func addKeyboard(view: UIView) {
let numericKeyboard = KeyboardVC(nibName: "NumericKeyboardVC", bundle: nil)
view.addSubview(numericKeyboard.view)
addChild(numericKeyboard)
}
#IBAction func fivePercentedButtonPressed(_ sender: Any) {
discount = Double(discountTF.text!)! * 0.05
discountTF.text = "\(discount)"
print(discount)
}
#IBAction func tenPercentButtonPressed(_ sender: Any) {
discount = Double(discountTF.text!)! * 0.1
discountTF.text = "\(discount)"
print(discount)
}
#IBAction func fifteenPercentButtonPressed(_ sender: Any) {
discount = Double(discountTF.text!)! * 0.15
discountTF.text = "\(discount)"
print(discount)
}
#IBAction func twentyPercentButtonPressed(_ sender: Any) {
discount = Double(discountTF.text!)! * 0.2
discountTF.text = "\(discount)"
print(discount)
}
#IBAction func goButton(_ sender: Any) {
}
}
Change to
#objc func calculateTotal(_ tex:UITextField){ --- }