Resign First Responder - swift

I was wondering how I could get rid of my search bar whenever I switch to my detailView, so I don't have to keep pressing cancel on the Search Bar whenever I switch to the detailView.
Here is my detailView Code.
import UIKit
class DetailViewLemon: UIViewController {
var sentData1:String!
#IBOutlet weak var DetailCarMake: UILabel!
#IBOutlet weak var Zacks: UILabel!
#IBOutlet weak var TheStreet: UILabel!
#IBOutlet weak var MarketWatch: UILabel!
#IBOutlet weak var StockMaster: UILabel!
#IBOutlet weak var Nasdaq: UILabel!
#IBOutlet weak var InvestorPlace: UILabel!
#IBOutlet weak var Benzinga: UILabel!
#IBOutlet weak var Rating: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
DetailCarMake.text = sentData1
self.title = sentData1
if self.title == "Apple" {
Zacks.text = "Zacks Rank: Buy"
TheStreet.text = "The Street: Buy"
MarketWatch.text = "MarketWatch: Buy"
StockMaster.text = "StockMaster: Buy"
Nasdaq.text = "Nasdaq Rating: Buy"
InvestorPlace.text = "InvestorPlace Rating: Buy"
Benzinga.text = "Benzinga Rating: Buy"
Rating.text = "Buy"
}
if self.title == "Google" {
Zacks.text = "Goog Zacks Rank: Buy"
TheStreet.text = "Goog The Street: Buy"
MarketWatch.text = "MarketWatch: Buy"
StockMaster.text = "StockMaster: Hold"
Nasdaq.text = "Nasdaq Rating: Buy"
InvestorPlace.text = "InvestorPlace Rating: Hold"
Benzinga.text = "Benzinga Rating: Buy"
Rating.text = "Buy"
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

In prepareForSegue of your TableViewController you should call self.searchController.searchBar.resignFirstResponder() (replacing names of variables with whatever they actually are, as you didn't show that code.

You could also use "view.endEditing(true)" in your viewWillDisappear
func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
view.endEditing(true)
}
It closes keyboard regardless of whichever input is being FirstResponder

Related

The picture goes up because the description is long how can I fix this?

When the picture description is long, my picture disappears, I can't see it. How can I show full size of text and full size of images?
How can I scroll the text up and down?
FavoriteDetailViewController
import UIKit
import ProgressHUD
class FavoriteDetailViewController: UIViewController {
#IBOutlet weak var shortdescriptionLabel: UILabel!
#IBOutlet weak var favoriteImageView: UIImageView!
#IBOutlet weak var favoriteTitleLabel: UILabel!
#IBOutlet weak var descriptionLabel: UILabel!
#IBOutlet weak var nameField: UITextField!
var breed: Breed!
override func viewDidLoad() {
super.viewDidLoad()
populateView()
}
private func populateView() {
favoriteImageView.kf.setImage(with: breed.image?.asUrl)
favoriteTitleLabel.text = breed.name
descriptionLabel.text = breed.description
shortdescriptionLabel.text = breed.shortDescription
}
#IBAction func favoriteButton(_ sender: UIButton) {
guard let name = nameField.text?.trimmingCharacters(in: .whitespaces),
!name.isEmpty else {
ProgressHUD.showError("Please enter your name")
return
}
print("Hello \(name)")
}
}
I made the text smaller but it's very illegible
I dropped the spacing, it looks bad too
I want to make the whole text look nice and not spoil the picture. What is the solution? Is it possible to move the label up and down?

pass data from tableviewcontroller to another tableviewcontroller in swift

I have a form I am creating
this form gets filled with textfields the user inputs. After answering all the questions a button pops up to save.
I am having a problem making this tableviewcontroller to pass the data to a new tableviewcontroller. I'm stuck and not sure how to go about this.
import UIKit
class TableViewController: UITableViewController, UITextFieldDelegate {
#IBOutlet weak var saveBtn: UIButton!
#IBOutlet var firstNameField: UITextField!
#IBOutlet var middleNameField: UITextField!
#IBOutlet weak var lastNameField: UITextField!
#IBOutlet weak var addressField: UITextField!
#IBOutlet weak var aptNumField: UITextField!
#IBOutlet weak var cityField: UITextField!
#IBOutlet weak var stateField: UITextField!
#IBOutlet weak var zipField: UITextField!
#IBOutlet weak var phoneOneField: UITextField!
#IBOutlet weak var phoneTwoField: UITextField!
#IBOutlet weak var allergiesField: UITextField!
#IBOutlet weak var DobField: UILabel!
#IBOutlet weak var sexField: UILabel!
#IBOutlet weak var hospitalField: UITextField!
#IBOutlet weak var doctorField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
//Notifications to push datepicker
NotificationCenter.default.addObserver(forName: .saveDateTime, object: nil, queue: OperationQueue.main) { (notification) in
let dateVc = notification.object as! DatePopupViewController
self.DobField.text = dateVc.formattedDate
}
//Notifications to push genderpicker
NotificationCenter.default.addObserver(forName: .saveGender, object: nil, queue: OperationQueue.main) { (notification) in
let genderVc = notification.object as! GenderPopupViewController
self.sexField.text = genderVc.selectedGender
}
updateWidthsForLabels(labels: labels)
}
//Save Button Function
func textFieldDidChange(_ textField: UITextField) {
if textField == firstNameField || textField == lastNameField || textField == middleNameField || textField == addressField || textField == lastNameField || textField == cityField || textField == cityField || textField == stateField || textField == zipField || textField == phoneOneField || textField == phoneTwoField || textField == allergiesField {
saveBtn.isHidden = true
} else {
saveBtn.isHidden = false
}
}
#IBAction func saveBtnPressed(_ sender: Any) {
performSegue(withIdentifier: "saveFirstPageSegue", sender: self)
}
}
what about starting creating a model:
Form.swift
struct Form {
var firstname: String?
var middlename: String?
....
var doctor: String?
init(firstname: String, middlename: String, ..., doctor: String) {
self.firstname = firstname
self.middlename = middlename
...
self.doctor = doctor
}
}
now you can create this form instance when saving and pushing the data to the new VC:
yourCurrentForm.swift
#IBAction func saveBtnPressed(_ sender: Any) {
let formData = Form(firstname: firstNameField.text, middlename: middleNameField.text, ..., doctor: doctorField.text)
let newVC = myNewViewController()
newVC.form = formData
self.navigationController?.pushViewController(newVC, animated: true)
}
NewViewController.swift
class myNewViewController: UIViewController {
var form: Form?
.....
}
UPDATE:
Here is the repo: https://github.com/FlorianLdt/LFEasyDelegate
If you have some question just ask me
Hope it helps.
First Option - Structs - Preferred
Make use of Structs :
struct Manager
{
static var value : String = ""
}
Noe Update value of that function by just calling
Manager.value = "newValue"
Access that value anywhere Assign it to other Variables
let newStr : String = Manager.value
Second Option - AppDelegate - Not ideal
Create new object in AppDelegate
Now create a new object to access appDelegate
let appDel = UIApplication.shared.delegate as! AppDelegate
Access Value and update as below
appDel.Frequency = 1.0
Third Option - NSObjectClass
Create a new NSObject class as below
//Instance created when NSObject class is first time loaded in memory stack
static let shared = wrapperClass()
//Create a value to access Globally in Object class
var newValueInClass : String = ""
Now time to access that created Object
wrapperClass.shared.newValueInClass = "iosGeek"
Now Anywhere write this Line
print(wrapperClass.shared.newValueInClass)
Console Output
Better to use struct classes to manage data globally

Update labels from unwind segue

I'm trying to change the labels of a viewController after a certain action is taken from a modal view which triggers an unwind segue.
Once unwind segue happens the labels of the current view (the one which the modal was covering) should be changed.
My current attempt at doing this is resulting in a "unexpectedly found nil while unwrapping an Optional value" error. Here is the code:
class DataViewController: UIViewController {
var experiment: NSDictionary?
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var bodyLabel: UILabel!
#IBOutlet weak var tlRightLine: UIImageView!
#IBOutlet weak var tlLeftLine: UIImageView!
#IBOutlet weak var brRightLine: UIImageView!
#IBOutlet weak var brLeftLine: UIImageView!
#IBOutlet weak var bodyTest: UITextView!
#IBAction func removeExperimentSegue(unwindSegue:UIStoryboardSegue) {
removeExperiment = true
titleLabel.text = "Done"
bodyLabel.text = "Done"
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if let dict: NSDictionary = experiment {
if let title = dict.objectForKey("title") as? String {
self.titleLabel!.text = title
}
if let body = dict.objectForKey("body") as? String {
self.bodyTest!.text = body
}
} else {
self.titleLabel!.text = ""
self.bodyLabel!.text = ""
}
}
}
What am I doing wrong?
I did! I ended up using a global boolean variable. I set it true on the initial load of the menu and then had it flip to false during the unwind segue.
var removeExperiment = false
class DataViewController: UIViewController {
#IBAction func removeExperimentSegue(unwindSegue:UIStoryboardSegue) {
removeExperiment = true
}
if removeExperiment == true {
doneLabel.text = "You've completed this experiment. You won't see it again unless you hit 'Reset' from the Home menu."
}
}
Hope that helps!

Compose Email with multiple uitextfield (swift)

How do I compose an email through Swift with multiple UITextField? It seems like I can only enter one data (named UITextField) under messageBody. How do can I add multiple UITextField to my messageBody?
import UIKit
import CoreData
import MessageUI
class EmailTableViewController: UITableViewController, MFMailComposeViewControllerDelegate, UITextFieldDelegate {
#IBOutlet weak var name: UITextField!
#IBOutlet weak var phone: UITextField
#IBOutlet weak var email: UITextField!
#IBOutlet weak var base: UITextField!
#IBOutlet weak var rig: UITextField!
#IBOutlet weak var wellhead: UITextField!
#IBOutlet weak var connector: UITextField!
#IBOutlet weak var size: UITextField!
#IBOutlet weak var depth: UITextField!
#IBOutlet weak var pressure: UITextField!
#IBOutlet weak var temp: UITextField!
#IBAction func SendEmailButton(sender: AnyObject) {
var emailTitle = "Interface Information"
var messageBody = name.text
var toRecipents = ["test.com"]
var mc: MFMailComposeViewController = MFMailComposeViewController()
mc.mailComposeDelegate = self
mc.setSubject(emailTitle)
mc.setMessageBody(messageBody, isHTML: false)
mc.setToRecipients(toRecipents)
self.presentViewController(mc, animated: true, completion: nil)
}
func mailComposeController(controller:MFMailComposeViewController, didFinishWithResult result:MFMailComposeResult, error:NSError) {
switch result.value {
case MFMailComposeResultCancelled.value:
println("Mail cancelled")
case MFMailComposeResultSaved.value:
println("Mail saved")
case MFMailComposeResultSent.value:
println("Mail sent")
case MFMailComposeResultFailed.value:
println("Mail sent failure: %#", [error.localizedDescription])
default:
break
}
self.dismissViewControllerAnimated(true, completion: nil)
}
You can just create a little helper function and put the fields in an array, like this:
func appendTextFromTextField(string: String, textField: UITextField) -> String {
return string + textField.text + "\n"
}
#IBAction func SendEmailButton(sender: AnyObject) {
var fields: [UITextField] = [name, phone, email, base, rig, wellhead, connector,
size, depth, pressure, temp]
var messageBody = ""
for f in fields {
messageBody = appendTextFromTextField(messageBody, textField: f)
}
// etc.
}

Swift- Adding Two UI Numbers then Output in Label

I can do this in C++/C, Objective C and Playground. I cannot get this to work in Swift when I try to make the App.
Can someone help out please?
//
// ViewController.swift
// Simple Mathemtical Functions_Swift
//
// Created by on 7/01/2015.
// Copyright (c) 2015 . All rights reserved.
//
import UIKit
class ViewController: UIViewController {
#IBOutlet var labelResult: UILabel!
#IBOutlet var Number2: UILabel!
#IBOutlet var Number1: UILabel!
#IBOutlet var field1: [UITextField]!
#IBOutlet var field2: [UITextField]!
#IBAction func Calculate(sender: AnyObject) {
labelResult.text = "\()"}
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.
}
}
If field1 and field2 and just UITextFields then [UITextField]! should be changed to UITextField!. [UITextField] indicates an array of UITextFields.
#IBOutlet var labelResult: UILabel!
#IBOutlet var Number2: UILabel!
#IBOutlet var Number1: UILabel!
#IBOutlet var field1: UITextField!
#IBOutlet var field2: UITextField!
#IBAction func Calculate(sender: AnyObject) {
var a = (field1.text as NSString).floatValue
var b = (field2.text as NSString).floatValue
var sum = a + b
labelResult.text = "\(sum)"
}
Maybe you're having trouble because field1.text is a String? not an NSString.
#IBAction func Calculate(sender: AnyObject) {
labelResult.text = "\((field1.text as NSString).floatValue + (field2.text as NSString).floatValue)"
}