Adding score and highscore in swift - ios

Im making this Quiz game with pictures on it.
Im trying to add score. Always when you press the right answer, you get one score and when you press wrong answer you must restart the game (that i have been done).
my problem is that where ever I'm trying to put this code, its giving all kind of errors.
So this is the code for highscore:
Score++
ScoreLabel.text = NSString(format: "Score: %i", Score)
if (Score > HighScore){
HighScore = Score
HighScoreLabel.text = NSString(format: "HighScore : %i", HighScore)
and i have put that on this place to the code:
import UIKit
class ViewController: UIViewController {
#IBOutlet var QuestionImage : UIImageView!
#IBOutlet var QuestionLabel: UILabel!
#IBOutlet var Button1: UIButton!
#IBOutlet var Button2: UIButton!
#IBOutlet var Button3: UIButton!
#IBOutlet var Button4: UIButton!
#IBOutlet var Restart: UIButton!
#IBOutlet var LabelEnd: UILabel!
#IBOutlet var ScoreLabel: UILabel!
#IBOutlet var HighScoreLabel: UILabel!
var CorrectAnswer = String()
var Score = 0
var HighScore = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Hide()
RandomQuestions()
HideRestart()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func RandomQuestions(){
var RandomNumber = arc4random() % 2
RandomNumber += 1
switch(RandomNumber){
case 1:
QuestionImage.image = UIImage(named: (“image.jpg"))
QuestionLabel.text = “question?"
Button1.setTitle(“answer", forState: UIControlState.Normal)
Button2.setTitle(“answer", forState: UIControlState.Normal)
Button3.setTitle(“answer", forState: UIControlState.Normal)
Button4.setTitle(“answer", forState: UIControlState.Normal)
CorrectAnswer = "1"
break
case 2:
QuestionImage.image = UIImage(named: (“image2.jpg"))
QuestionLabel.text = “question?"
Button1.setTitle(“answer", forState: UIControlState.Normal)
Button2.setTitle(“answer", forState: UIControlState.Normal)
Button3.setTitle(“answer", forState: UIControlState.Normal)
Button4.setTitle(“answer", forState: UIControlState.Normal)
CorrectAnswer = "3"
break
default:
break
}
}
func Hide(){
LabelEnd.hidden = true
}
func UnHide(){
LabelEnd.hidden = false
}
func HideButtons(){
Button1.hidden = true
Button2.hidden = true
Button3.hidden = true
Button4.hidden = true
}
func HideRestart(){
Restart.hidden = true
}
func UnHideRestart(){
Restart.hidden = false
}
#IBAction func Button1Action(sender: AnyObject) {
UnHide()
if (CorrectAnswer == "1"){
RandomQuestions()
Hide()
HideRestart()
Score++
ScoreLabel.text = NSString(format: "Score: %i", Score)
if (Score > HighScore){
HighScore = Score
HighScoreLabel.text = NSString(format: "HighScore : %i", HighScore)
}
else{
LabelEnd.text = "You are wrong!"
HideButtons()
UnHideRestart()
}
}
#IBAction func Button2Action(sender: AnyObject) {
UnHide()
if (CorrectAnswer == "2"){
RandomQuestions()
Hide()
HideRestart()
Score++
ScoreLabel.text = NSString(format: "Score: %i", Score)
if (Score > HighScore){
HighScore = Score
HighScoreLabel.text = NSString(format: "HighScore : %i", HighScore)
}
else{
LabelEnd.text = "You are wrong!"
HideButtons()
UnHideRestart()
}
}
#IBAction func Button3Action(sender: AnyObject) {
UnHide()
if (CorrectAnswer == "3"){
RandomQuestions()
Hide()
HideRestart()
Score++
ScoreLabel.text = NSString(format: "Score: %i", Score)
if (Score > HighScore){
HighScore = Score
HighScoreLabel.text = NSString(format: "HighScore : %i", HighScore)
}
else{
LabelEnd.text = "You are wrong!"
HideButtons()
UnHideRestart()
}
}
#IBAction func Button4Action(sender: AnyObject) {
UnHide()
if (CorrectAnswer == "4"){
RandomQuestions()
Hide()
HideRestart()
Score++
ScoreLabel.text = NSString(format: "Score: %i", Score)
if (Score > HighScore){
HighScore = Score
HighScoreLabel.text = NSString(format: "HighScore : %i", HighScore)
}
else{
LabelEnd.text = "You are wrong!"
HideButtons()
UnHideRestart()
}
}
}
So always when you press the right button its score and always when wrong, its giving a label "You are wrong!".
And there is these kind of cases for the questions and at the end there is the CorrectAnswer.
I have 4 answer buttons. I also have 2 View Controllers, other is the start screen and second is the game and i would like to get the highscore label on the start view and the score label to the game view.
Thank you very much forehand!

All your ButtonXAction functions are missing their closing parentheses ). You've probably missed one line when copy-pasting...

Related

Quiz app option button background color change

When we click on the wrong option in the quiz application, the background color is red and the background color of the correct option is green. how can I do that? My model :
struct QuizModel {
let q : String
let a : [String]
let correctAnswer : Int
}
my question :
QuizModel(q: "Aşağıdakilerden hangisi ilk yardımın amaçlarından biri değildir?", a: [
"A) İlaçla tedavi etmek","B) Durumun kötüleşmesini önlemek","C) Hayati tehlikeyi ortadan kaldırmak","D) Yaşamsal fonksiyonların sürdürülmesini sağlamak"], correctAnswer: 0)
answer func :
func checkAnswer(userAnswer : Int)-> Bool {
if userAnswer == quiz[questionNumber ].correctAnswer {
return true
}else{
return false
}
}
user tapped option button :
#objc func TappedButton(_ sender : UIButton){
let userAnswer = sender.tag
let userRightGot = quizBrains.checkAnswer(userAnswer: userAnswer)
if userRightGot {
sender.backgroundColor = .green
score += 1
scoreLabel.text = "\(score)"
}else{
sender.backgroundColor = .red
failScore += 1
failScoreLabel.text = "\(failScore)"
}
The method affects only the currently tapped button, you have to update the state of the other buttons, too.
Something like this, button0-button3 are the references to the buttons, you have to add IBOutlets if there are none.
var buttons = [button0, button1, button2, button3]
// please name methods with starting lowercase letter
#objc func tappedButton(_ sender : UIButton) {
let userAnswer = sender.tag
let correctAnswer = quiz[questionNumber].correctAnswer
for button in buttons {
button.backgroundColor = button.tag == correctAnswer ? .green : .red
}
if userAnswer == correctAnswer {
score += 1
scoreLabel.text = "\(score)"
} else {
failScore += 1
failScoreLabel.text = "\(failScore)"
}
}

TabBar tappedIcon unTappedIcon Issue

When i tapped on my TabBar's first image it should be highlighted like the below image -
enter image description here
But when i tap on the first icon it's doing nothing, tap on the second icon it's highlighting the first icon, tap on the 3rd icon highlighting it's previous icon (second icon) and so on. It might be an indexing problem. Need some help to find this issue. Thank you. My TabBar current view-
enter image description here
Here is my code -
import UIKit
class ViewController: BaseViewController {
//MARK: Outlets
#IBOutlet var warningsIcon: UIImageView!
#IBOutlet var incidentsIcon: UIImageView!
#IBOutlet var notificationsIcon: UIImageView!
#IBOutlet var myMessagesIcon: UIImageView!
#IBOutlet var warningsTitle: UILabel!
#IBOutlet var incidentsTitle: UILabel!
#IBOutlet var notificationsTitle: UILabel!
#IBOutlet var myMessagesTitle: UILabel!
#IBOutlet var containerView: UIView!
//MARK: PROPERTIES
var previousSelectedIcon:UIImageView!
var previousSeelctedTitle:UILabel!
var previousIndex:Int!
var currentIndex:Int!
var previousVc:UIViewController!
fileprivate var i = 0
open var subViewController:UIViewController?
var unTappedIcon = ["warnings","incidents","notifications","my-messages"]
var tappedIcon = ["warnings_tapped","Incidents_tapped","notifications_tapped","myMessages_tapped"]
override func viewDidLoad() {
super.viewDidLoad()
addSlideMenuButton()
// Do any additional setup after loading the view, typically from a nib.
previousVc = self;
previousSelectedIcon = warningsIcon
previousSeelctedTitle = warningsTitle
previousIndex = 0;
currentIndex = 0;
//place sub view controller if any
placeSubViewControllerIfNeeded()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//place sub view controller if needed
func placeSubViewControllerIfNeeded() -> Void{
if let vc = subViewController {
vc.view.frame = self.containerView.frame
self.addChildViewController(vc)
//vc.view.frame = self.view.frame
self.containerView.addSubview(vc.view)
self.view.sendSubview(toBack: vc.view)
}
}
//MARK: For Tab bar
func updateTapView(title:UILabel, icon:UIImageView) {
previousSeelctedTitle.textColor = UIColor(red:0.60, green:0.60, blue:0.60, alpha:1.0)
previousSelectedIcon.image = UIImage.init(named: unTappedIcon[previousIndex])
title.textColor = UIColor(red:0.26, green:0.18, blue:0.49, alpha:1.0)
icon.image = UIImage.init(named: tappedIcon[currentIndex])
}
func removePreviousViewController() {
previousVc.willMove(toParentViewController: nil)
previousVc.view.removeFromSuperview()
previousVc.removeFromParentViewController()
}
func getStoryBoardByIndentifier(identifier:String)->UIStoryboard {
return UIStoryboard.init(name: identifier, bundle: nil)
}
func showSubViewContrller(subViewController:UIViewController) {
self.addChildViewController(subViewController)
subViewController.view.frame = containerView.frame
self.containerView.addSubview(subViewController.view)
subViewController.didMove(toParentViewController: self)
previousVc = subViewController
}
//Mark:- Action button for warnings
#IBAction func onClickWarnings(_ sender: UITapGestureRecognizer) {
print("Hi there i am just a warning")
self.warningsIcon.image = UIImage.init(named: "warnings_tapped")
previousIndex = currentIndex
currentIndex = 0
updateTapView( title: warningsTitle, icon: warningsIcon)
previousSeelctedTitle = warningsTitle
previousSelectedIcon = warningsIcon
if i > 0{
removePreviousViewController()
print("i am already removed")
}
let storyBoard = getStoryBoardByIndentifier(identifier: "warnings")
let vc = storyBoard.instantiateViewController(withIdentifier: "WarningsViewController") as! WarningsViewController
showSubViewContrller(subViewController: vc)
i += 1
}
//Mark:- Action button for warnings
#IBAction func onClickIncidents(_ sender: UITapGestureRecognizer) {
print("Hi there i am just a warning")
self.incidentsIcon.image = UIImage.init(named: "Incidents_tapped")
previousIndex = currentIndex
currentIndex = 1
updateTapView( title: incidentsTitle, icon: incidentsIcon)
previousSeelctedTitle = incidentsTitle
previousSelectedIcon = incidentsIcon
if i > 0{
removePreviousViewController()
print("i am already removed")
}
let storyBoard = getStoryBoardByIndentifier(identifier: "incidents")
let vc = storyBoard.instantiateViewController(withIdentifier: "IncidentsViewController") as! IncidentsViewController
showSubViewContrller(subViewController: vc)
i += 1
}
//Mark:- Action button for warnings
#IBAction func onClickNotifications(_ sender: UITapGestureRecognizer) {
print("Really true")
self.notificationsIcon.image = UIImage.init(named: "notifications_tapped")
previousIndex = currentIndex
currentIndex = 2
updateTapView(title: notificationsTitle, icon: notificationsIcon)
previousSeelctedTitle = notificationsTitle
previousSelectedIcon = notificationsIcon
if i > 0 {
removePreviousViewController()
print("I am already removed")
}
let storyBoard = getStoryBoardByIndentifier(identifier: "notifications")
let vc = storyBoard.instantiateViewController(withIdentifier: "NotificationsViewController") as! NotificationsViewController
showSubViewContrller(subViewController: vc)
i += 1
}
//Mark:- Action button for warnings
#IBAction func onClickMyMessages(_ sender: UITapGestureRecognizer) {
print("ha ha..i believe in that")
self.myMessagesIcon.image = UIImage.init(named: "myMessages_tapped")
previousIndex = currentIndex
currentIndex = 3
updateTapView(title: myMessagesTitle , icon: myMessagesIcon)
previousSeelctedTitle = myMessagesTitle
previousSelectedIcon = myMessagesIcon
if i > 0 {
removePreviousViewController()
print("i am alreday removed")
}
let storyBoard = getStoryBoardByIndentifier(identifier: "myMessages")
let vc = storyBoard.instantiateViewController(withIdentifier: "MyMessagesViewController") as! MyMessagesViewController
showSubViewContrller(subViewController: vc)
i += 1
}
}
Looks like you are adding view ineach viewcotroller which you want to show as if a tab bar item.. this might not be the right way to do.. what you can do is make your custom tabbar controller
class SampleViewController: UITabBarController {
#IBOutlet var tabBarView: UIView!
#IBOutlet weak var item1Btn: UIButton!
#IBOutlet weak var item2Btn: UIButton!
#IBOutlet weak var item3Btn: UIButton!
#IBOutlet weak var item4Btn: UIButton!
#IBOutlet weak var item5Btn: UIButton!
let item1Image = #imageLiteral(resourceName: "profileUnselected")
let item1Selected = #imageLiteral(resourceName: "profile")
let item2Image = #imageLiteral(resourceName: "notificationUnselected")
let item2Selected = #imageLiteral(resourceName: "notificationSelected")
let item3Image = #imageLiteral(resourceName: "game")
let item3Selected = #imageLiteral(resourceName: "game")
let item4Image = #imageLiteral(resourceName: "cookbooksUnselected")
let item4Selected = #imageLiteral(resourceName: "cookbooks")
let item5Image = #imageLiteral(resourceName: "searchTabUnselected")
let item5Selected = #imageLiteral(resourceName: "searchTabSelected")
let unSelectedColor = UIColor.lightGray
let selectedColor = UIColor.white
let appColor = UIColor(red: 22.0/255.0, green: 168.0/255.0, blue: 225.0/255.0, alpha: 1.0)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if UIDevice().userInterfaceIdiom == .phone {
switch UIScreen.main.nativeBounds.height {
case 2436:
offsetHeight = 44.0
default:
print("unknown")
}
}
addTabView()
}
func addTabView() {
Bundle.main.loadNibNamed("TabBarView", owner: self, options: nil)
tabBarView.frame = CGRect(x:
0 , y: Helper.getScreenHeight() - AppConstants.kTabBarheight - offsetHeight, width: Helper.getScreenWidth(), height: AppConstants.kTabBarheight)
self.view.addSubview(tabBarView)
self.item3Btn.sendActions(for: .touchUpInside) //here i showed my third tab bar item initially
}
#IBAction func tabBarBtnClick(_ sender: UIButton) {
var isViewToChange = false
let currentIndex = self.selectedIndex
var tochangeIndex = sender.tag
self.item1Btn.setImage(item1Image, for: .normal)
self.item2Btn.setImage(item2Image, for: .normal)
self.item3Btn.setImage(item3Image, for: .normal)
self.item4Btn.setImage(item4Image, for: .normal)
self.item5Btn.setImage(item5Image, for: .normal)
switch sender.tag {
case 0:
self.item1Btn.setImage(item1Selected, for: .normal)
if currentIndex != 0{
isViewToChange = true
tochangeIndex = 0
}
else{
(self.viewControllers?[currentIndex] as! UINavigationController).popToRootViewController(animated: true)
}
case 1:
self.item2Btn.setImage(item2Selected, for: .normal)
if currentIndex != 1{
isViewToChange = true
tochangeIndex = 1
}
else{
(self.viewControllers?[currentIndex] as! UINavigationController).popToRootViewController(animated: true)
}
case 2:
if currentIndex != 2{
isViewToChange = true
tochangeIndex = 2
}
else{
(self.viewControllers?[currentIndex] as! UINavigationController).popToRootViewController(animated: true)
}
case 3:
self.item4Btn.setImage(item4Selected, for: .normal)
if currentIndex != 3{
isViewToChange = true
tochangeIndex = 3
}
else{
(self.viewControllers?[currentIndex] as! UINavigationController).popToRootViewController(animated: true)
}
case 4:
self.item5Btn.setImage(item5Selected, for: .normal)
if currentIndex != 4{
isViewToChange = true
tochangeIndex = 4
}
else{
(self.viewControllers?[currentIndex] as! UINavigationController).popToRootViewController(animated: true)
}
default:
break
}
if isViewToChange {
let _ = self.selectedViewController?.view
let _ = self.viewControllers?[tochangeIndex].view
self.selectedIndex = tochangeIndex
}
}
func hideTabbar() {
self.tabBar.isHidden = true
var frame = tabBarView.frame
frame.origin.y = Helper.getScreenHeight() + 200
tabBarView.frame = frame
}
func showTabbar() {
self.tabBar.isHidden = false
var frame = tabBarView.frame
frame.origin.y = Helper.getScreenHeight() - AppConstants.kTabBarheight - offsetHeight
tabBarView.frame = frame
}
}
here i have aded methods for you to either show the tab bar of hide as we push into the stack of each tab bar item..
Here added few images for your understanding
and also dont forgot to set the tag for each button in tab bar view, so that when any button clicked, same method is called and we handle it from there

Have a button subtract the value of the next button I press. Swift

I have seven buttons labeled 1-7 in my counting app. The counting starts at 0, then when I press a number, it is added onto 0. So if I press 6, the count is at 6. Then I press 3, and the count is now at 9. Now I want to include a subtraction button so that I can go down by hitting the subtract button, then picking the value of my choice. So if I hit the subtraction button followed by the number 2, the count would go back to 7.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var Score: UILabel!
var number = 0
#IBAction func oneButton(_ sender: UIButton) {
var number1 = number + 1
number = number1
var realNumber = String(number)
Score.text = realNumber
}
#IBAction func twoButton(_ sender: UIButton) {
var number1 = number + 2
number = number1
var realNumber = String(number)
Score.text = realNumber
}
#IBAction func threeButton(_ sender: UIButton) {
var number1 = number + 3
number = number1
var realNumber = String(number)
Score.text = realNumber
}
#IBAction func fourButton(_ sender: UIButton) {
var number1 = number + 4
number = number1
var realNumber = String(number)
Score.text = realNumber
}
#IBAction func fiveButton(_ sender: UIButton) {
var number1 = number + 5
number = number1
var realNumber = String(number)
Score.text = realNumber
}
#IBAction func sixButton(_ sender: UIButton) {
var number1 = number + 6
number = number1
var realNumber = String(number)
Score.text = realNumber
}
#IBAction func sevenButton(_ sender: UIButton) {
var number1 = number + 7
number = number1
var realNumber = String(number)
Score.text = realNumber
}
#IBAction func foulButton(_ sender: UIButton) {
}
}
I am not sure what code I should be putting in the foulButton function. Thank you in advance.
I'd start by giving "tags" to each of ur buttons with their numeric value, then you can use a single function for all. Then it will be very easy to simulate a subtraction.
var subtraction = false
#IBAction func buttonAction(_ sender: UIButton) {
var change = sender.tag
if subtraction {
change = change * (-1)
subtraction = false
}
number = number + change
Score.text = String(number)
}
#IBAction func foulButton(_ sender: UIButton) {
subtraction = !subtraction
}
I think you want to make the button for adding and subtracting values you can make a simple Generic function for this task just like that:-
var count = 0
func addNumber(number:Int) {
count = count+number
var realNumber = String(number)
print(realNumber)
Score.text = realNumber
}
func subtractNumber(number:Int) {
count = count-number
var realNumber = String(number)
print(realNumber)
Score.text = realNumber
}
addNumber(number: 4) //function call from your button
subtractNumber(number: 2) //by respective values

How to end a switch case

I have created a class with random questions however the switch statement does not end and the questions keep going in a loop. How do I prevent this from happening and to display another page once all 4 questions randomly have been completed?
import UIKit
class ThirdViewController: UIViewController {
#IBOutlet weak var Question: UILabel!
#IBOutlet weak var Ans1: UIButton!
#IBOutlet weak var Ans2: UIButton!
#IBOutlet weak var Ans3: UIButton!
#IBOutlet weak var Ans4: UIButton!
#IBOutlet weak var Result: UILabel!
#IBOutlet weak var Next: UIButton!
var correctAns = String()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Hide()
Random()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func Random(){
var RandomNumber = arc4random() % 4
RandomNumber += 1
switch (RandomNumber) {
case 1:
Question.text = "Where does minal lives?"
Ans1.setTitle("dubai", for: UIControlState.normal)
Ans2.setTitle("london", for: UIControlState.normal)
Ans3.setTitle("india", for: UIControlState.normal)
Ans4.setTitle("japan", for: UIControlState.normal)
correctAns = "2"
break
case 2:
Question.text = "What is my name?"
Ans1.setTitle("Sunil", for: UIControlState.normal)
Ans2.setTitle("Harish", for: UIControlState.normal)
Ans3.setTitle("Rohit", for: UIControlState.normal)
Ans4.setTitle("Minal", for: UIControlState.normal)
correctAns = "4"
break
case 3:
Question.text = "How old are you?"
Ans1.setTitle("22", for: UIControlState.normal)
Ans2.setTitle("32", for: UIControlState.normal)
Ans3.setTitle("21", for: UIControlState.normal)
Ans4.setTitle("28", for: UIControlState.normal)
correctAns = "1"
break
case 4:
Question.text = "What are you studying?"
Ans1.setTitle("Computer Science", for: UIControlState.normal)
Ans2.setTitle("Java", for: UIControlState.normal)
Ans3.setTitle("Bio", for: UIControlState.normal)
Ans4.setTitle("Business", for: UIControlState.normal)
correctAns = "3"
break
default:
Result.text = "Finished"
break
}
}
func Hide(){
Result.isHidden = true
Next.isHidden = true
}
func Unhide(){
Result.isHidden = false
Next.isHidden = false
}
#IBAction func Ans1Action(_ sender: Any) {
Unhide()
if (correctAns == "1"){
Result.text = "Correct!"
}
else{
Result.text = "Try Again"
}
}
#IBAction func Ans2Action(_ sender: Any) {
Unhide()
if (correctAns == "2"){
Result.text = "Correct!"
}
else{
Result.text = "Try Again"
}
}
#IBAction func Ans3Action(_ sender: Any) {
Unhide()
if (correctAns == "3"){
Result.text = "Correct!"
}
else{
Result.text = "Try Again"
}
}
#IBAction func Ans4Action(_ sender: Any) {
Unhide()
if (correctAns == "4"){
Result.text = "Correct!"
}
else{
Result.text = "Try Again"
}
}
#IBAction func NextAction(_ sender: Any) {
Random()
Hide()
}
}
You need to keep a counter of the number of questions already asked. The switch (RandomNumber) will always enter one of the case statements, because RandomNumber is always in the range 1...4.
So, what you need to do is add an instance variable
private var questionCounter = 0
and modify the NextAction function, something like this:
#IBAction func NextAction(_ sender: Any) {
questionCounter += 1
if questionCounter >= 4 {
Result.text = "Finished"
// or whatever...
}
else {
Random()
Hide()
}
}
Keep in mind that by performing an arc4random() each time, the same question may appear more than once.
Create an array of Int indexes from 1 to 4.
Extract an element from the array and display that item. When the array is empty, stop:
Something like this:
var questionIndexes = [1, 2, 3, 4]
if questionIndexes.count > 0 {
let random = Int(arc4random_uniform(Uint32(questionIndexes.count)))
let index = questionIndexes.remove(at: index)
askQuestionAtIndex(index)
}
(You'll have to adjust the code to fit in with your existing code, but that's the basic idea.)

Changing Button Text to a number

I am trying a small project in swift.
I have two labels where i get random numbers each time i click a button.
My question is how can I change the title of the button, to the addition of my two random numbers.
Here is the code:
#IBOutlet var number1: UILabel!
#IBOutlet var number2: UILabel!
#IBOutlet var result: UILabel!
var randomNumber1:Int = 0
var randomNumber2:Int = 0
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func generate(sender: AnyObject) {
randomNumber1 = Int(arc4random())%11
number1.text = "\(randomNumber1)"
randomNumber2 = Int(arc4random())%11
number2.text = "\(randomNumber2)"
result.text = "\((randomNumber1) + (randomNumber2))"
}
Try this:
#IBAction func generate(sender: UIButton) {
randomNumber1 = Int(arc4random())%11
number1.text = "\(randomNumber1)"
randomNumber2 = Int(arc4random())%11
number2.text = "\(randomNumber2)"
result.text = "\((randomNumber1) + (randomNumber2))"
sender.setTitle("\((randomNumber1) + (randomNumber2))", forState: UIControlState.Normal)
}
You were missing this line
sender.setTitle("\((randomNumber1) + (randomNumber2))", forState: UIControlState.Normal)
Hope this helps.. :)
btn.setTitle("\(number)", forState: .Normal)
In your current code, you're changing the text of the result label, not the button. To change the UIButton sender's title, change your code to the following:
#IBAction func buttonPress(sender: UIButton) {
let randomNumber1 = Int(arc4random())%11
number1.text = "\(randomNumber1)"
let randomNumber2 = Int(arc4random())%11
number2.text = "\(randomNumber2)"
sender.setTitle("\((randomNumber1) + (randomNumber2))", forState: UIControlState.Normal)
}
Try this code, instead of anyobject use UIButton
#IBAction func generate(sender: UIButton) {
randomNumber1 = Int(arc4random())%11
number1.text = "\(randomNumber1)"
randomNumber2 = Int(arc4random())%11
number2.text = "\(randomNumber2)"
result.text = "\((randomNumber1) + (randomNumber2))"
//Just add this line in the code
sender.setTitle(result.text, forState: UIControlState.Normal)
}

Resources