import UIKit
let alert = UIAlertController(title: "Warning",
message: "Your number is too big.",
preferredStyle: .alert)
class ViewController: UIViewController {
// Verbindungen zu Storyboard
#IBAction func rechnerEntry(_ sender: Any) {
}
#IBOutlet weak var resultLabel: UILabel!
#IBOutlet weak var buttons: UIButton!
#IBAction func clear(_ sender: Any) {
calculatorLabel.text = ""
number = 0
}
override func viewDidLoad() {
super.viewDidLoad()
buttons.backgroundColor = UIColor.gray
}
// Aufführung happyFuncs
func happyFunc(number: Int) -> Int {
var myNum = number
var sum = 0
while myNum > 0 {
let x = myNum % 10
sum += (x * x)
myNum /= 10
}
return sum
}
// happyCheckerFunc
func happyChecker(_ x: Int) -> Bool {
var alreadychecked: Set<Int> = Set()
var result = happyFunc(number: x)
while !alreadychecked.contains(result) {
if result == 1 {
resultLabel.text = "your number is a happy number"
return true
}
alreadychecked.insert(result)
result = happyFunc(number: result)
}
resultLabel.text = "your number is a unhappy number"
return false
}
// Eingabe Werte
var number = 0
var x = 0
#IBOutlet weak var calculatorLabel: UILabel!
var isTypingNumber = false
// Nummer getippt
#IBAction func numberTapped(_ sender: UIButton) {
let number = sender.currentTitle ?? (sender.titleLabel?.text ?? "0")
if isTypingNumber {
calculatorLabel.text = calculatorLabel.text! + number
} else {
calculatorLabel.text = number
isTypingNumber = true
}
}
// Überprüfung happy?
#IBAction func happycheck(_ sender: UIButton) {
number = Int(calculatorLabel.text!)!
x = number
if x > 9999999999999999 {
alert.addAction(UIAlertAction(title: "OK",
style: .default,
handler: { _ in
print("OK tap")
}))
present(alert, animated: true, completion: nil)
}
func happyFunc(number: Int) -> Int {
var myNum = number
var sum = 0
while myNum > 0 {
let x = myNum % 10
sum += (x * x)
myNum /= 10
}
return sum
}
func happyChecker(_ x: Int) -> Bool {
var alreadychecked: Set<Int> = Set()
var result = happyFunc(number: x)
while !alreadychecked.contains(result) {
if result == 1 {
resultLabel.text = "your number is a happy number"
return true
}
alreadychecked.insert(result)
result = happyFunc(number: result)
}
resultLabel.text = "your number is a unhappy number"
return false
}
happyChecker(x)
}
}
storyboard
Hey I wanted to ask you how I can implement the Swipe back Gesture in Swift. So I want that the user start at the Home View Controller and then he can tap on the "happy number Rechner"-Button and then the calculator View Controller appears. Like the same way with the transitions in the Settings App of iOS. And if you swipe left the Home View should appear again. Thank you!
You will need NavigationController, and ViewController
You can find and add this such like when you add a button.
After that click your Button, hold on the option button your keyboard, and pull together the first-and secondviewcontroller, now add you a navigationcontroller( you will see 2 screen, just delete a tableview controller screen) and don't forget to put a new way your arrow.(nav.controller first)
Related
I've built a likert quiz and I'm trying to create a results page that looks like the second view controller. So far all I've been able to return is the score and personality ranked (first view controller).
I'm not sure how I can show the quiz results in order. I basically would want to rank them and adjust the cells, while showing the point total but I have no clue what to do.
class SurveyResultsViewController: UITableViewController {
#IBOutlet var lblSortedScores : [UILabel]!
#IBOutlet var sortedTitle : [UILabel]!
#IBOutlet weak var cellFinishButton : UITableViewCell!
var survey: LikertSurvey?
var points = [0, 0, 0, 0]
var results: [(Int, Int)] = []
override func viewDidLoad() {
super.viewDidLoad()
UserDefaults.standard.setValue(points, forKey: "points")
self.setResults()
self.initUI()
}
private func setResults() {
for (index, point) in points.enumerated() {
results.append((index, point))
}
results.sort { (result1, result2) -> Bool in
return result1.1 > result2.1
}
}
private func initUI() {
for i in 0 ..< results.count {
let title = survey!.questionCategories[results[i].0]
lblSortedScores[i].text = "\(title) = \(results[i].1) points"
sortedTitle[i].text = "\(title)"
}
let finishButtonTap = UITapGestureRecognizer(target: self, action: #selector(self.finishButtonTapped(_:)))
cellFinishButton.addGestureRecognizer(finishButtonTap)
self.navigationItem.hidesBackButton = false
}
#objc func finishButtonTapped(_ sender: UITapGestureRecognizer) {
self.survey?.completed = true
let alertController = UIAlertController(title: "Congratulations! You earned 100 XP from completing this quest!", message: "", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Ok",
style: .default) { action in
self.performSegue(withIdentifier: "unwindToSectionTableView", sender: self)
})
self.present(alertController, animated: true, completion: nil)
}
}
Try restructuring your code like so
var results: [(index: Int, points: Int)] = []
...
private func setResults() {
for (index, point) in points.enumerated() {
results.append((index, point))
}
results.sort{ $0.points > $1.points }
self.initUI()
}
I have two Random numbers generating in ViewDidLoad. I Want to plus these two numbers and the result should be checked in a button with data of a input field. my problem is that I do not know how to transfer result to the function CheckResultBtn . now it does not recognise result.
here is My codes and I really appreciate any kinds of help
class ViewController: UIViewController {
#IBOutlet weak var lblRandomNumOne: UILabel!
#IBOutlet weak var lblRandomNumTwo: UILabel!
#IBOutlet weak var KidsField: UITextField!
#IBOutlet weak var Showresult: UILabel!
#IBOutlet weak var CheckResult: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let x = Int.random(in: 0 ..< 10)
lblRandomNumOne.text = String(x);
let y = Int.random(in: 0 ..< 10)
lblRandomNumTwo.text = String(y);
let result = x + y;
CheckResultBtn(result) //not sure about this
}
#IBAction func CheckResultBtn(_ sender: Any)
{
if (KidsField != nil)
{
let kidsresult = Int(KidsField.text!) ;
if (result == kidsresult)
{
Showresult.text = "Bravo";
}
else
{
Showresult.text = "Try Again!"
}
}
}
}
declare the variable "result" before the viewDidload function
var result : Int!
then proceed to perform the operation on the variable in your viewDidload and you can get rid of this line
CheckResultBtn(result)
and you should be able to access the result variable in your IBAction function
You can try
#IBAction func checkResultBtn(_ sender: Any) {
displayRes(Int(kidsField.text!)!)
}
func displayRes(_ result:Int) {
showresult.text = result == kidsresult ? "Bravo" : "Try Again!"
}
Then inside viewDidLoad
displayRes(x+y)
create a new function instead of using action Method
like this :
func CheckResultBtn(_ result : Int) {
if (KidsField != nil)
{
let kidsresult = Int(KidsField.text!) ;
if (result == kidsresult)
{
Showresult.text = "Bravo";
}
else
{
Showresult.text = "Try Again!"
}
}
}
or create a variable
var result : Int?
assign a value
result = x + y;
and use inside the action Method
var result : Int?
override func viewDidLoad() {
super.viewDidLoad()
let x = Int.random(in: 0 ..< 10)
lblRandomNumOne.text = String(x);
let y = Int.random(in: 0 ..< 10)
lblRandomNumTwo.text = String(y);
result = x + y;
}
#IBAction func CheckResultBtn(_ sender: Any) {
if (KidsField != nil)
{
let kidsresult = Int(KidsField.text!) ;
if (result == kidsresult)
{
Showresult.text = "Bravo";
}
else
{
Showresult.text = "Try Again!"
}
}
}
I'm doing a calculator for school I finished everything but in the end the priority of calculation is not respected for example when I do : 2 + 2 * 2 it should be 6 but in my app it tells me 8, anyone have an idea how can I do that ? you will find in my code my model and my controller :
class viewControllerUtilities: UIViewController {
var stringNumbers: [String] = [String()]
var operators: [String] = ["+"]
var formerResult: Double?
var index = 0
var isExpressionCorrect: Bool{
if let stringNumber = stringNumbers.last{
if stringNumber.isEmpty{
if stringNumbers.count == 1 {
return false
}
return false
}
}
return true
}
var canAddOperator: Bool {
if let stringNumber = stringNumbers.last{
if stringNumber.isEmpty && formerResult == nil{
return false
}
}
return true
}
var canAddDecimal: Bool{
if let strings = stringNumbers.last{
if strings.contains(".") || strings.isEmpty{
return false
}
}
return true
}
func addDecimal(){
if let stringNumber = stringNumbers.last{
var stringNumberDecimal = stringNumber
stringNumberDecimal += "."
stringNumbers[stringNumbers.count-1] = stringNumberDecimal
}
}
func calculateTotal() -> Double{
var total : Double = 0
for (i, stringNumber) in stringNumbers.enumerated(){
if let number = Double(stringNumber){
switch operators[i]{
case "+":
total += number
case "-":
total -= number
case "x":
total *= number
case "/":
total /= number
default:
break
}
}
}
formerResult = total
clear()
return total
}
func clear(){
stringNumbers = [String()]
operators = ["+"]
index = 0
}
func allClear(){
clear()
formerResult = nil
}
func sendOperand(operand: String, number: String) {
operators.append(operand)
stringNumbers.append(number)
}
func addNewNumber(_ newNumber: Int){
if let stringNumber = stringNumbers.last{
var stringNumberMutable = stringNumber
stringNumberMutable += "\(newNumber)"
stringNumbers[stringNumbers.count-1] = stringNumberMutable
}
}
func roundResult(_ result: Double?){
if roundEvaluation(result!){
let rounded = Int(result!)
stringNumbers = ["\(rounded)"]
formerResult = nil
}
}
func roundEvaluation(_ result: Double) -> Bool{
if result.truncatingRemainder(dividingBy: 1) == 0{
return true
}
return false
}
}
and my controller :
class ViewController: UIViewController {
// MARK: - Properties
var CountOnMeU = viewControllerUtilities()
// MARK: - Outlets
#IBOutlet weak var textView: UITextView!
#IBOutlet var numberButtons : [UIButton]!
#IBOutlet var operators: [UIButton]!
#IBOutlet weak var point: UIButton!
// MARK: - Action
#IBAction func tappedNumberButton(_ sender: UIButton) {
for (i, numberButton) in numberButtons.enumerated() where sender == numberButton{
CountOnMeU.addNewNumber(i)
updateDisplay()
}
}
#IBAction func tappedPointButton(_ sender: Any){
if CountOnMeU.canAddDecimal{
CountOnMeU.addDecimal()
updateDisplay()
} else {
showAlert(message: "Vous ne pouvez pas mettre 2 points")
}
}
#IBAction func equal() {
if !CountOnMeU.isExpressionCorrect{
showAlert(message: "opération invalide")
} else {
let total = CountOnMeU.calculateTotal()
textView.text! += "\n =\(total)"
}
}
#IBAction func operandButtonTapped(_ sender: UIButton){
performOperation(operand: (sender.titleLabel?.text!)!)
}
#IBAction func allClear(_ sender: UIButton) {
CountOnMeU.allClear()
textView.text = "0"
}
// MARK: - Methods
func addNewNumber(message: String){
let alertVC = UIAlertController(title: "Erreur", message: message, preferredStyle: .alert)
alertVC.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
self.present(alertVC, animated: true, completion: nil)
}
func updateDisplay() {
var text = ""
let stack = CountOnMeU.stringNumbers.enumerated()
for (i, stringNumber) in stack {
// Add operator
if i > 0 {
text += CountOnMeU.operators[i]
}
// Add number
text += stringNumber
}
textView.text = text
}
func showAlert(message: String){
let AlertVC = UIAlertController(title: "Erreur", message: message, preferredStyle: .alert)
AlertVC.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
self.present(AlertVC,animated: true, completion: nil)
}
func performOperation(operand: String){
if CountOnMeU.canAddOperator{
let result = CountOnMeU.formerResult
if result != nil {
CountOnMeU.roundResult(result)
updateDisplayForResultReuse(operand: operand)
} else {
CountOnMeU.sendOperand(operand: operand, number: "")
updateDisplay()}
} else {
self.showAlert(message: "Expression incorrecte")
}
}
func updateDisplayForResultReuse(operand: String){
updateDisplay()
CountOnMeU.sendOperand(operand: operand, number: "")
updateDisplay()
}
}
I am wondering how I should save the users progress in my quiz game. Every time the user closes the app it resets. Here's my code:
import UIKit
import GoogleMobileAds
class ViewController: UIViewController, GADBannerViewDelegate {
//Place your instance variables here
let allQuestions = QuestionBank()
var pickedAnswer : Bool = false
var questionNumber : Int = 0
var score : Int = 0
let googleAdTestID: String = "ca-app-pub-3940256099942544/2934735716"
#IBOutlet weak var questionLabel: UILabel!
#IBOutlet weak var scoreLabel: UILabel!
#IBOutlet weak var bannerView: GADBannerView!
#IBOutlet weak var progressLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
print("Google Mobile Ads SDK version: " + GADRequest.sdkVersion() )
bannerView.adUnitID = googleAdTestID
bannerView.rootViewController = self
bannerView.load(GADRequest())
nextQuestion()
}
#IBAction func skipButton(_ sender: Any) {
skip()
}
func skip() {
if score <= 4 {
}
else if score >= 5 {
questionNumber = questionNumber + 1
nextQuestion()
score = score - 5
scoreLabel.text = "Coins: \(score)"
}
}
#IBAction func answerPressed(_ sender: AnyObject) {
if sender.tag == 1 {
pickedAnswer = true
}
else if sender.tag == 2 {
pickedAnswer = false
}
checkAnswer()
questionNumber = questionNumber + 1
nextQuestion()
}
func updateUI() {
scoreLabel.text = "Coins: \(score)"
progressLabel.text = "Question Number: \(questionNumber + 1)"
}
func nextQuestion() {
if questionNumber <= 37 {
questionLabel.text = allQuestions.list[questionNumber].questionText
updateUI()
}
else {
let alert = UIAlertController(title: "Awesome", message: "You have finished all the questions!! Do you want to start over?", preferredStyle: .alert)
let restartAction = UIAlertAction(title: "Restart", style: .default, handler: { (UIAlertAction) in
self.startOver()
})
alert.addAction(restartAction)
present(alert, animated: true, completion: nil)
}
}
func checkAnswer() {
let correctAnswer = allQuestions.list[questionNumber].answer
if correctAnswer == pickedAnswer {
print("Correct!")
ProgressHUD.showSuccess("Correct!!")
// varible += 1 same as varible = varible + 1
score += 1
}
else {
print("wrong!")
ProgressHUD.showError("Wrong!!")
}
}
func startOver() {
questionNumber = 0
nextQuestion()
score = 0
scoreLabel.text = "Score: 0"
}
}
Save
// save necessory information using UserDefaults
// Add this code at your business logic
let database = UserDefaults.standard
let questionNumber = 2
database.set(questionNumber, forKey: "LAST_ANSWERED_QUESTION_NUMBER")
let score = 23
database.set(score, forKey: "QUIZ_SCORE")
let sync = database.synchronize()
if sync{
print("userdefaults - sync done")
}else{
print("userdefaults - failed to sync")
}
Fetch
//access stored values from UserDefaults
// Add this code at your business logic
let database = UserDefaults.standard
if let lastAnswredQuestion = database.value(forKey: "LAST_ANSWERED_QUESTION_NUMBER") as? Int{
print("LAST_ANSWERED_QUESTION_NUMBER \(lastAnswredQuestion)")
}
if let scored = database.value(forKey: "QUIZ_SCORE") as? Int{
print("QUIZ_SCORE \(scored)")
}
NOTE: The data will be stored until the app is installed, if the user deletes the app then whole data will vanish from UserDefaults.
I'm a beginner to Swift and generally Xcode. Thank you in advance for your time and help :)
I am doing a Quiz App, and I try to have random questions... I have a function to generate random numbers that I tried to apply in viewDidLoad()... unfortunately I can not guess how to use that information in his variable "var currentQuestion = 0"
This is the code:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
generateRandomNumber(0, 9, 10)
}
override func viewDidAppear(_ animated: Bool) {
newQuestion()
}
// Quiz//
let questions = ["Q1","Q2","Q3","Q4","Q5"]
let answers = [["A","2","3"],["B","2","3"],["C","2","3"],["D","2","3"],["E","2","3"]]
//Variables
var currentQuestion = 0
var rightAnswerPlacement:UInt32 = 0
//Generate Random Numbers
func generateRandomNumber(_ from:Int, _ to:Int, _ qut:Int?) -> [Int] {
var myRandomNumbers = [Int]() //All our generated numbers
var numberOfNumbers = qut //How many numbers to generate
let lower = UInt32(from) //Generate from this number..
let higher = UInt32(to+1) //To this one
if numberOfNumbers == nil || numberOfNumbers! > (to-from) + 1 {
numberOfNumbers = (to-from) + 1
}
while myRandomNumbers.count != numberOfNumbers {
let myNumber = arc4random_uniform(higher - lower) + lower
if !myRandomNumbers.contains(Int(myNumber)) {
myRandomNumbers.append(Int(myNumber))
}
}
return myRandomNumbers
}
//Label
#IBOutlet weak var lbl: UILabel!
//Button
#IBAction func action(_ sender: AnyObject) {
if (sender.tag == Int(rightAnswerPlacement)) {
print ("RIGHT!")
} else {
print ("WRONG!!!!!!")
}
if (currentQuestion != questions.count) {
newQuestion()
} else {
}
}
//Function that displays new question
func newQuestion() {
lbl.text = questions[currentQuestion]
rightAnswerPlacement = arc4random_uniform(3)+1
//Create a button
var button:UIButton = UIButton()
var x = 1
for i in 1...3 {
//Create a button
button = view.viewWithTag(i) as! UIButton
if (i == Int(rightAnswerPlacement)) {
button.setTitle(answers[currentQuestion][0], for: .normal)
} else {
button.setTitle(answers[currentQuestion][x], for: .normal)
x = 2
}
}
currentQuestion += 1
}
Any idea that how will be possible to resolve?
First you need to store the array of random questions that you generate (side note you appear to try to generate 10 random numbers but have only 5 questions).
Then instead of using the currentQuestion directly you use that to access the question in the array.
So change it to this:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
questionArray = generateRandomNumber(0, 9, 10)
}
override func viewDidAppear(_ animated: Bool) {
newQuestion()
}
// Quiz//
let questions = ["Q1","Q2","Q3","Q4","Q5"]
let answers = [["A","2","3"],["B","2","3"],["C","2","3"],["D","2","3"],["E","2","3"]]
//Variables
var currentQuestion = 0
var rightAnswerPlacement:UInt32 = 0
var questionArray: [Int] = [] // Just an initial value
//Generate Random Numbers
func generateRandomNumber(_ from:Int, _ to:Int, _ qut:Int?) -> [Int] {
var myRandomNumbers = [Int]() //All our generated numbers
var numberOfNumbers = qut //How many numbers to generate
let lower = UInt32(from) //Generate from this number..
let higher = UInt32(to+1) //To this one
if numberOfNumbers == nil || numberOfNumbers! > (to-from) + 1 {
numberOfNumbers = (to-from) + 1
}
while myRandomNumbers.count != numberOfNumbers {
let myNumber = arc4random_uniform(higher - lower) + lower
if !myRandomNumbers.contains(Int(myNumber)) {
myRandomNumbers.append(Int(myNumber))
}
}
return myRandomNumbers
}
//Label
#IBOutlet weak var lbl: UILabel!
//Button
#IBAction func action(_ sender: AnyObject) {
if (sender.tag == Int(rightAnswerPlacement)) {
print ("RIGHT!")
} else {
print ("WRONG!!!!!!")
}
if (currentQuestion != questions.count) {
newQuestion()
} else {
}
}
//Function that displays new question
func newQuestion() {
lbl.text = questions[questionArray[currentQuestion]]
rightAnswerPlacement = arc4random_uniform(3)+1
//Create a button
var button:UIButton = UIButton()
var x = 1
for i in 1...3 {
//Create a button
button = view.viewWithTag(i) as! UIButton
if (i == Int(rightAnswerPlacement)) {
button.setTitle(answers[questionArray[currentQuestion]][0], for: .normal)
} else {
button.setTitle(answers[questionArray[currentQuestion]][x], for: .normal)
x = 2
}
}
currentQuestion += 1
}
(I think the code is correct but I'm currently running some tests in Xcode so can't check. If there is a problem leave a comment.)