Hide keyboard in view after inputting values? - ios

I have a small calculator built into 3 different views. On all the calcuulators, I would like to have the keyboard disappear upon either tapping anywhere on the screen or upon pressing the button to calucate a value. Ive researched several sources and have become confused on how to implement any code for this. My calculator code is below. Thanks in advance!
class Calculators: UIViewController {
#IBOutlet var fluidIn: UITextField!
#IBOutlet var timeIn: UITextField!
#IBOutlet var dripIn: UITextField!
#IBOutlet var dripResult: UILabel!
#IBOutlet var weight: UITextField!
#IBOutlet var etomidate: UILabel!
#IBOutlet var succ: UILabel!
#IBOutlet var roc: UILabel!
#IBOutlet var ketamine: UILabel!
#IBOutlet var lbsIn: UITextField!
#IBOutlet var KgIn: UITextField!
#IBOutlet var KgOut: UILabel!
#IBOutlet var LbsOut: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func calculate(sender: UIButton) {
let Number2 = Double(weight.text!)
let etommult = (0.3)
let etomresult = Number2! * etommult
etomidate.text = "\(etomresult)"
etomidate.text = NSString(format:"%2.1f mg",etomresult)as String;
let Number3 = Double(weight.text!)
let succmult = (2.0)
let succresult = Number3! * succmult
succ.text = "\(succresult)"
succ.text = NSString(format: "%2.1f mg",succresult)as String;
let Number4 = Double(weight.text!)
let rocmult = (1.0)
let rocresult = Number4! * rocmult
roc.text = "\(rocresult)"
roc.text = NSString(format: "%2.1f mg",rocresult)as String;
let Number5 = Double(weight.text!)
let fentmult = (2.0)
let fentresult = Number5! * fentmult
ketamine.text = "\(fentresult)"
ketamine.text = NSString(format: "%2.1f mg",fentresult)as String;
}
#IBAction func KgConv(_ sender: Any) {
let kg = Double(lbsIn.text!)
let kgmult = (2.2)
let kgresult = kg! / kgmult
KgOut.text = "\(kgresult)"
KgOut.text = NSString(format: "%2.1f kg",kgresult)as String;
}
#IBAction func LbsConv(_ sender: Any) {
let lbs = Double(KgIn.text!)
let lbsmult = (2.2)
let lbsresult = lbs! * lbsmult
LbsOut.text = "\(lbsresult)"
LbsOut.text = NSString(format: "%2.1f kg",lbsresult)as String;
}
#IBAction func dripCalc(_ sender: Any) {
let cc = Double(fluidIn.text!)
let min = Double(timeIn.text!)
let fct = Double(dripIn.text!)
let dripRes = (cc! * fct!) / min!
dripResult.text = "\(dripRes)"
dripResult.text = NSString(format: "%2.1f gtts/min",dripRes)as String;
}

Call the below code whenever and wherever you want to hide the keyboard in viewController.
view.endEditing(true)

Related

Check if input countains numbers in 2 fields in xcode

So i recently tried to create a very simple calcylator in xcode, the problem i have is when i press the calculate button when there is no numbers there the app crashes, and when i put anything that isnt a number there and press the calculate button it also crash, and i know it crash cause it cant convert nothing/non numbers into a double, but how do i check if it is numbers in the textfields and if it is it will show the result off the
equation and if there is no number it will just set the textfeilds to nothing
(faktor1.text = "") (faktor2.text = "") ...
well it looks like this right now (ränka ut means calculate)
here is the code i used,
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var faktor1: UITextField!
#IBOutlet weak var faktor2: UITextField!
#IBOutlet weak var result: UILabel!
#IBOutlet weak var calculatebutton: UIButton!
#IBOutlet weak var clearui: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
result.text = ""
calculatebutton.layer.cornerRadius = 25.0
result.layer.cornerRadius = 25.0
clearui.layer.cornerRadius = 25.0
}
#IBAction func calculate( sender: Any) {
let input1 = Double(faktor1.text!)!
let input2 = Double(faktor2.text!)!
let calculation = input1 * input2
result.text = "(calculation)"
}
#IBAction func clearfnc( sender: Any) {
result.text = ""
faktor1.text = ""
faktor2.text = ""
}
}
You can simply unwrap your optionals the Swift way, instead of using ! (force unwrap)
This is an example using guard:
#IBAction func calculate(sender: Any) {
guard
let input1String = faktor1.text,
let input2String = faktor1.text,
let input1 = Double(input1String),
let input2 = Double(input2String)
else {
faktor1.text = ""
faktor1.text = ""
return
}
let calculation = input1 * input2
result.text = "\(calculation)"
}

How to check if a user inputed answer has letters, and if so, how would you just default that answer into a 0?

Heres the code I have so far, now when a user inputs any letter, my label display nothing, what I would like to figure out is how to turn that nothing "", into a 0. I tried doing an if statement on my "label.txt ="'s but that didn't pan out. What would be a better way of finding my desired results?
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var game1: UITextField!
#IBOutlet weak var game2: UITextField!
#IBOutlet weak var game3: UITextField!
#IBOutlet weak var series: UILabel!
#IBOutlet weak var average: UILabel!
#IBOutlet weak var high: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func calculate(_ sender: Any) {
self.view.endEditing(true)
guard
let text1 = game1.text,
let text2 = game2.text,
let text3 = game3.text
else { return }
guard
let game1Results = Int(text1),
let game2Results = Int(text2),
let game3Results = Int(text3)
else { return }
let gameResultsArray = [game1Results, game2Results, game3Results]
let sumArray = gameResultsArray.reduce(0, +)
let positiveArray = gameResultsArray.filter {
(item: Int) -> Bool in return item > 0
}
var avgArrayValue = 0
if positiveArray.count == 0
{
avgArrayValue = 0
}else {
avgArrayValue = sumArray / positiveArray.count
}
series.text = "\(sumArray)"
average.text = "\(avgArrayValue)"
if let maximumVal = gameResultsArray.max() {
high.text = String(maximumVal)
}
}
}
Here is what you need, convert String to Int and give the default 0. Instead of using the guard let return use this method:
Instead of this:
guard let game1Results = Int(text1) else { return }
Use this:
let game1Results = Int(text1) ?? 0

How to find the average of just the user inputs above 0

so I'm trying to find the average of my results using only user inputed values above 0. I'm not sure how I would check the results in the array to find out which values are above 0 and exclude them from the calculation in swift.
class ViewController: UIViewController {
#IBOutlet weak var game1: UITextField!
#IBOutlet weak var game2: UITextField!
#IBOutlet weak var game3: UITextField!
#IBOutlet weak var series: UILabel!
#IBOutlet weak var average: UILabel!
#IBOutlet weak var high: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func calculate(_ sender: Any) {
self.view.endEditing(true)
guard
let text1 = game1.text,
let text2 = game2.text,
let text3 = game3.text
else { return }
guard
let game1Results = Int(text1),
let game2Results = Int(text2),
let game3Results = Int(text3)
else { return }
let gameResultsArray = [game1Results, game2Results, game3Results]
let sumArray = gameResultsArray.reduce(0, +)
let avgArrayValue = sumArray / gameResultsArray.count
series.text = "\(sumArray)"
average.text = "\(avgArrayValue)"
if let maximumVal = gameResultsArray.max() {
high.text = String(maximumVal)
}
}
}
To filter out all values above 0 in an array, use the filter method. This will return a subset of your original array with all values passing the condition declared inside -
var demoArray = [-1, -8, 0, 1, 5 ,6]
var positiveArray = demoArray.filter { (item: Int) -> Bool in
return item > 0
}
print(positiveArray) // [1, 5, 6]
simply you can use filter
..
let sumArray = gameResultsArray.filter({$0 > 0})
let avgArrayValue = sumArray.reduce(0, +) / sumArray.count

print .get in my label using alamofire json swift 3.0

Is being a few weeks and I'm still stuck with this problem here. I'm having a mind block with Api. I'm quite new on this and I really need help.
I have those lines done. The single task is: Get data from my API and post it in my label. I've 4 files/classes being used.
UserProfile
import Foundation
import SwiftyJSON
class UserProfileWork: NSObject {
var workHistoryId = String()
var jobSeekerId = String()
var jobPosition = String()
var employer = String()
var workHistoryName = String()
var responsabilities = String()
var reasonForLeaving = String()
var currentPosition = Int()
var startMonth = String()
var startYear = String()
var endMonth = String()
var endYear = String()
init?(workDict: [String: JSON]){
guard let workHistoryId = workDict["work_history_id"]?.string,
let jobSeekerId = workDict["job_seeker_id"]?.string,
let jobPosition = workDict["position"]?.string,
let employer = workDict["employer"]?.string,
let workHistoryName = workDict["work_history_name"]?.string,
let responsabilities = workDict["responsibilities"]?.string,
let reasonForLeaving = workDict["reason_for_leaving"]?.string,
let currentPosition = workDict["is_current_position"]?.toInt,
let startMonth = workDict["start_month"]?.string,
let startYear = workDict["start_year"]?.string,
let endMonth = workDict["end_month"]?.string,
let endYear = workDict["end_year"]?.string else { return nil}
self.workHistoryId = workHistoryId
self.jobSeekerId = jobSeekerId
self.jobPosition = jobPosition
self.employer = employer
self.workHistoryName = workHistoryName
self.responsabilities = responsabilities
self.reasonForLeaving = reasonForLeaving
self.currentPosition = currentPosition
self.startMonth = startMonth
self.startYear = startYear
self.endMonth = endMonth
self.endYear = endYear
}
}
Api + Userprofile
import Foundation
import Alamofire
import SwiftyJSON
extension API {
class func userProfile(completion: #escaping(_ error: Error?, _ userProfile: [UserProfile]?) ->Void) {
let url = URLs.jobSeekerTest90
guard let api_token = helper.getApiToken() else {
completion(nil, nil)
return
}
let headers: HTTPHeaders = [
"Authorization": "Bearer \(api_token)",
"Accept": "application/json"
]
let parameters = [
"api_token": api_token
]
Alamofire.request(url, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: headers)
.responseJSON{ response in
switch response.result{
case .failure(let error):
completion(error, nil)
print(error)
case .success(let value):
let json = JSON(value)
print(json)
guard let dataDict = json["data"]["jobSeeker"].array else{
completion(nil, nil)
return
}
var userProfile = [UserProfile]()
for data in dataDict {
if let data = data.dictionary, let profileData = UserProfile.init(dict: data){
userProfile.append(profileData)
}
completion(nil, userProfile)
}
}
}
}
}
And my view Controller ( I had tableview before but I decided to use only scrollView + labeles because I just need to display those single data)
import UIKit
import Alamofire
class ProfileViewController: UIViewController{
#IBOutlet weak var leadingConstraint: NSLayoutConstraint!
#IBOutlet weak var menuView: UIView!
#IBOutlet weak var menuProfilePicture: UIImageView!
#IBOutlet weak var myAccountImageMenu: UIImageView!
#IBOutlet weak var switchProfileImageMenu: UIImageView!
#IBOutlet weak var signOutImageMenu: UIImageView!
//User profile
#IBOutlet weak var userProfilePicture: UIImageView!
#IBOutlet weak var userNameLabel: UILabel!
#IBOutlet weak var userNameJobPositionLabel: UILabel!
//quick facts
#IBOutlet weak var quickFactsLabel: UILabel!
#IBOutlet weak var userLocationImage: UIImageView!
#IBOutlet weak var userLocationLabel: UILabel!
#IBOutlet weak var userWorkExpImage: UIImageView!
#IBOutlet weak var userWorkExpLabel: UILabel!
#IBOutlet weak var educationImage: UIImageView!
#IBOutlet weak var educationLabel: UILabel!
#IBOutlet weak var infoImage: UIImageView!
#IBOutlet weak var infoAboutLabel: UILabel!
// most recent jobs
#IBOutlet weak var recentJobTitleLabel: UILabel!
#IBOutlet weak var userJobTitleLabel: UILabel!
#IBOutlet weak var companyNameLabel: UILabel!
#IBOutlet weak var startFinishLabel: UILabel!
//Education
#IBOutlet weak var highestEducLabel: UILabel!
#IBOutlet weak var programNameLabel: UILabel!
#IBOutlet weak var schoolNameLabel: UILabel!
#IBOutlet weak var startFinishEducLabel: UILabel!
var iconArray: [String]!
var userProfileData : [UserProfile] = []
var userProfileEducation : [UserProfileEducation] = []
var userProfileWork : [UserProfileWork] = []
var menuShowing = false
override func viewDidLoad() {
super.viewDidLoad()
iconArray = ["currentLocationIcon", "dataIcon", "educationIcon", "infiIcon"]
leadingConstraint.constant = -520
menuView.layer.shadowOpacity = 1
menuView.layer.shadowRadius = 5
menuProfilePicture.layer.cornerRadius = 35
menuProfilePicture.clipsToBounds = true
userProfilePicture.layer.cornerRadius = 55
userProfilePicture.clipsToBounds = true
handleRefresh()
userData()
}
private func userData(){
self.userNameLabel.text = ""
self.userNameJobPositionLabel.text = "Job Title"
self.userLocationLabel.text = "User Location"
self.userWorkExpLabel.text = "Work Experience"
self.educationLabel.text = "Education"
self.infoAboutLabel.text = "About me. More about me"
self.userJobTitleLabel.text = "Job title again"
self.companyNameLabel.text = "Company Name"
self.startFinishLabel.text = "12 sep 2010 - 11 sep 2017"
self.programNameLabel.text = "web and mobile app dev"
self.schoolNameLabel.text = "school name"
self.startFinishEducLabel.text = "finished at"
}
//reusable cells
private func handleRefresh(){
API.userProfile { (error: Error?, userProfileData: [UserProfile]?) in
if let userProfileData = userProfileData {
self.userProfileData = userProfileData
}
}
API.userEducation { (error: Error?, userEducation : [UserProfileEducation]?) in
if let userEducation = userEducation {
self.userProfileEducation = userEducation
}
}
API.userWork { (error: Error?, userWork: [UserProfileWork]?) in
if let userWork = userWork {
self.userProfileWork = userWork
}
}
}
//Scroll hidden menu
#IBAction func scrollMenu(_ sender: Any) {
if(menuShowing){
leadingConstraint.constant = -520
UIView.animate(withDuration: 0.5, animations: {
self.view.layoutIfNeeded()
})
}else{
leadingConstraint.constant = 0
UIView.animate(withDuration: 0.5, animations: {
self.view.layoutIfNeeded()
})
}
menuShowing = !menuShowing
}
override func dismissKeyboard() {
view.endEditing(true)
}
}
I really need help on this guys. Please, help me!
I made some changes and It worked.
import UIKit
import SwiftyJSON
class UserProfile: NSObject{
var userID = String()
var JobSeekerId = String()
var userFstName = String()
var userLstName = String()
var userFullName = String()
var userJobTitle = String()
var userAbout = String()
var userLocation = String()
var userRecentSalary = String()
var userSalaryHiExpect = String()
var userSalaryLoExpect = String()
var userWebsiteUrl = String()
var userEmail = String()
var userMobile = String()
init?(dict: [String: Any]){
guard let userID = dict["user_id"] as? String,
let jobSeekerId = dict["job_seeker_id"] as? String,
let userFstName = dict["first_name"] as? String,
let userLstName = dict["last_name"] as? String,
let userFullName = dict["job_seeker_name"] as? String,
let userJobTitle = dict["personal_job_title"] as? String,
let userAbout = dict["about"] as? String,
let userLocation = dict["seekingLocations"] as? String,
let userRecentSalary = dict["most_recent_salary"] as? String,
let userSalaryHiExpect = dict["salary_expectation_high"] as? String,
let userSalaryLoExpect = dict["salary_expectation_low"] as? String,
let userWebsiteUrl = dict["website_url"] as? String,
let userEmail = dict["contact_email"] as? String,
let userMobile = dict["contact_mobile"] as? String else { return nil }
self.userID = userID
self.JobSeekerId = jobSeekerId
self.userFstName = userFstName
self.userLstName = userLstName
self.userFullName = userFullName
self.userJobTitle = userJobTitle
self.userAbout = userAbout
self.userLocation = userLocation
self.userRecentSalary = userRecentSalary
self.userSalaryHiExpect = userSalaryHiExpect
self.userSalaryLoExpect = userSalaryLoExpect
self.userWebsiteUrl = userWebsiteUrl
self.userEmail = userEmail
self.userMobile = userMobile
}
}
API+userProfile
import Foundation
import Alamofire
import SwiftyJSON
extension API {
class func userProfile(completion: #escaping(_ error: Error?, _ userProfile: UserProfile?) ->Void) {
let url = URLs.jobSeekerTest90
guard let api_token = helper.getApiToken() else {
completion(nil, nil)
return
}
let headers: HTTPHeaders = [
"Authorization": "Bearer \(api_token)",
"Accept": "application/json"
]
let parameters = [
"api_token": api_token
]
Alamofire.request(url, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: headers)
.responseJSON{ response in
switch response.result{
case .failure(let error):
completion(error, nil)
print(error)
case .success(let value):
let json = JSON(value)
print(json)
guard let dataDict = json["data"]["jobSeeker"].dictionaryObject else{
completion(nil, nil)
return
}
var userProfile = UserProfile(dict: dataDict)
completion(nil, userProfile)
}
}
}
}
ViewController
import UIKit
import Alamofire
class ProfileViewController: UIViewController{
#IBOutlet weak var leadingConstraint: NSLayoutConstraint!
#IBOutlet weak var menuView: UIView!
#IBOutlet weak var menuProfilePicture: UIImageView!
#IBOutlet weak var menuProfileName: UILabel!
#IBOutlet weak var myProfileJobTitle: UILabel!
#IBOutlet weak var myAccountImageMenu: UIImageView!
#IBOutlet weak var switchProfileImageMenu: UIImageView!
#IBOutlet weak var signOutImageMenu: UIImageView!
//User profile
#IBOutlet weak var userProfilePicture: UIImageView!
#IBOutlet weak var userNameLabel: UILabel!
#IBOutlet weak var userNameJobPositionLabel: UILabel!
//quick facts
#IBOutlet weak var quickFactsLabel: UILabel!
#IBOutlet weak var userLocationImage: UIImageView!
#IBOutlet weak var userLocationLabel: UILabel!
#IBOutlet weak var userWorkExpImage: UIImageView!
#IBOutlet weak var userWorkExpLabel: UILabel!
#IBOutlet weak var educationImage: UIImageView!
#IBOutlet weak var educationLabel: UILabel!
#IBOutlet weak var infoImage: UIImageView!
#IBOutlet weak var infoAboutLabel: UILabel!
// most recent jobs
#IBOutlet weak var recentJobTitleLabel: UILabel!
#IBOutlet weak var userJobTitleLabel: UILabel!
#IBOutlet weak var companyNameLabel: UILabel!
#IBOutlet weak var startFinishLabel: UILabel!
//Education
#IBOutlet weak var highestEducLabel: UILabel!
#IBOutlet weak var programNameLabel: UILabel!
#IBOutlet weak var schoolNameLabel: UILabel!
#IBOutlet weak var startFinishEducLabel: UILabel!
var iconArray: [String]!
var userProfileData : [UserProfile] = []
var userProfileEducation : [UserProfileEducation] = []
var userProfileWork : [UserProfileWork] = []
var menuShowing = false
override func viewDidLoad() {
super.viewDidLoad()
iconArray = ["currentLocationIcon", "dataIcon", "educationIcon", "infiIcon"]
leadingConstraint.constant = -520
menuView.layer.shadowOpacity = 1
menuView.layer.shadowRadius = 5
menuProfilePicture.layer.cornerRadius = 35
menuProfilePicture.clipsToBounds = true
userProfilePicture.layer.cornerRadius = 55
userProfilePicture.clipsToBounds = true
userData()
userWorkProfileData()
userEducationProfileData()
}
private func userData(){
API.userProfile { (error: Error?, userProfileData: UserProfile?) in
if let userProfileData = userProfileData {
self.myProfileJobTitle.text = userProfileData.userFullName
self.menuProfileName.text = userProfileData.userJobTitle
self.userNameLabel.text = userProfileData.userFullName
self.userNameJobPositionLabel.text = userProfileData.userJobTitle
self.userLocationLabel.text = userProfileData.userLocation
self.infoAboutLabel.text = userProfileData.userAbout
self.userJobTitleLabel.text = userProfileData.userJobTitle
}
}
}
//Scroll hidden menu
#IBAction func scrollMenu(_ sender: Any) {
if(menuShowing){
leadingConstraint.constant = -520
UIView.animate(withDuration: 0.5, animations: {
self.view.layoutIfNeeded()
})
}else{
leadingConstraint.constant = 0
UIView.animate(withDuration: 0.5, animations: {
self.view.layoutIfNeeded()
})
}
menuShowing = !menuShowing
}
override func dismissKeyboard() {
view.endEditing(true)
}
}

How To Fix: "Expression is Ambiguous".

I am trying to create an app that can help you calculate sales tax on an item. Of course the app requires multiplication But I keep encountering the error:
"Type of expression is ambiguous without more context"
Can you help me? I'm new to swift so also try to explain why I am incorrect. This is my code so far:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var Item: UITextField!
#IBOutlet weak var Tax: UITextField!
#IBOutlet weak var Answer: UITextField!
#IBAction func Calculate(_ sender: Any) {
let a = Item.text
let conversionRate = Tax
let b = Int(a!)! * conversionRate
Answer.text = ("\(b)")
}
}
Thanks!!
Your primary issue is your attempt to multiply an Int and a UITextField.
You attempt to create an Int from Item.text but you make no similar attempt to convert Tax.text to a number.
There are also many other issues with your code. You are using the ! operator too much and your app will crash as a result.
And your naming conventions need to be improved. Variables and methods should start with lowercase letters.
Here's your code as it should be written:
class ViewController: UIViewController {
#IBOutlet weak var item: UITextField!
#IBOutlet weak var tax: UITextField!
#IBOutlet weak var answer: UITextField!
#IBAction func calculate(_ sender: Any) {
if let itemStr = item.text, let taxStr = tax.text, let itemVal = Int(itemStr), let taxVal = Int(taxStr) {
let result = itemVal * texVal
answer.text = "\(result)"
} else {
answer.text = "Invalid values"
}
}
}
You're trying to multiply a variable of UITextField type with a variable of Int. Try this:
class ViewController: UIViewController {
#IBOutlet weak var Item: UITextField!
#IBOutlet weak var Tax: UITextField!
#IBOutlet weak var Answer: UITextField!
#IBAction func Calculate(_ sender: Any) {
guard let a = Int(Item.text ?? "0") else { return }
guard let conversionRate = Int(Tax.text ?? "0") else { return }
let b = a * conversionRate
Answer.text = ("\(b)")
}
}

Resources