Button function not handling the event properly when pressed? - swift

struct Question {
var Question : String!
var Answers : [String]!
var AnswerNumber : Int!
}
class LevelOne: SKScene {
var button = Button()
var buttons = [Button]()
let Question_met = UILabel(frame: CGRect(x: 0.3, y: 0.3, width: 40, height: 21))
var Questions = [Question]()
var QNumber = Int()
var buttonNames = [""]
var AnsNumber = Int()
let selectors:[Selector] = [#selector(handleButton1), #selector(handleButton2), #selector(handleButton3),#selector(handleButton4)]
override func didMove(to view: SKView) {
let background = SKSpriteNode(imageNamed: "background")
background.position = CGPoint(x: self.size.width/2, y: self.size.height/2)
background.zPosition = 0
self.addChild(background)
QuestionFunction()
ButtonFuction()
PickQuestion()
}
#objc func QuestionFunction(){
Questions = [Question(Question: "What is a BMW ?", Answers: ["Bat","Cat","Vehicle","Pat"], AnswerNumber: 2),
Question(Question: "What is a Boeing ?", Answers: ["Bat","Aircraft","Cat","Pat"], AnswerNumber: 1),
Question(Question: "What is a Ant ?", Answers: ["Insect","Cat","Insect","Nate"], AnswerNumber: 2),
Question(Question: "What is a Apple ?", Answers: ["Fruit","Cat","bat","Pat"], AnswerNumber: 0),
Question(Question: "Where is london ?", Answers: ["UK","USA","France","Germany"], AnswerNumber: 0),
Question(Question: "Where is New York ?", Answers: ["Canada","USA","France","Germany"], AnswerNumber: 2),
Question(Question: "where is Berlin ?", Answers: ["UK","USA","Italy","Germany "], AnswerNumber: 3),
Question(Question: "Where is Toronto ?", Answers: ["India","Africa","Canada","Norway"], AnswerNumber: 2),
Question(Question: "Where is Rome ?", Answers: ["Japan","China","Italy","Ireland"], AnswerNumber: 2),
Question(Question: "where is Chennai ?", Answers: ["India","Brazil","Swiss","Germany"], AnswerNumber: 0),]
Question_met.frame = CGRect(x: 330, y: 70, width: 200, height: 21)
Question_met.backgroundColor = UIColor.orange
Question_met.textColor = UIColor.white
Question_met.textAlignment = NSTextAlignment.center
Question_met.text = "What caused Global Warming ?"
self.view?.addSubview(Question_met)
}
#objc func ButtonFuction(){
let stacView = UIStackView()
stacView.spacing = 12
stacView.distribution = .fillEqually
stacView.axis = .horizontal
stacView.translatesAutoresizingMaskIntoConstraints = false
view!.addSubview(stacView)
buttonNames = ["One","Two","Three","Four"]
for name in buttonNames {
button = Button()
button.setTitle(name, for: .normal)
stacView.addArrangedSubview(button)
buttons.append(button)
}
for i in 0..<4{
button.addTarget(self, action: selectors[i], for: .touchUpInside)
}
NSLayoutConstraint.activate([stacView.centerXAnchor.constraint(equalTo: view!.centerXAnchor),stacView.centerYAnchor.constraint(equalTo: view!.centerYAnchor),stacView.widthAnchor.constraint(equalToConstant: 350),stacView.heightAnchor.constraint(equalToConstant:70)])
}
#objc func PickQuestion(){
if Questions.count > 0{
QNumber = 0
Question_met.text = Questions[QNumber].Question
AnsNumber = Questions[QNumber].AnswerNumber
for i in 0..<buttons.count{
buttons[i].setTitle(Questions[QNumber].Answers[i], for: .normal)
}
Questions.remove(at: QNumber)
}
else {
print("Done!")
}
}
#objc func handleButton1() {
if AnsNumber == 0 {
PickQuestion()
print("Correct!")
}
else {
print("You are Wrong!!!")
}
}
#objc func handleButton2(){
if AnsNumber == 1 {
PickQuestion()
print("Correct!")
}
else {
print("You are Wrong!!!")
}
}
#objc func handleButton3(){
if AnsNumber == 2 {
PickQuestion()
print("Correct!")
}
else {
print("You are Wrong!!!")
}
}
#objc func handleButton4(){
if AnsNumber == 3 {
PickQuestion()
print("Correct!")
}
else {
print("You are Wrong!!!")
}
}
}
The button action methods don't seem to be accurate in knowing which right answer button is being pressed while different number is assigned as answer for each question the methods seems to only move forward when pressing the last button.
Thank you in advance much appreciate the help.

Your problem is located in your ButtonFunction():
for name in buttonNames {
button = Button()
button.setTitle(name, for: .normal)
stacView.addArrangedSubview(button)
buttons.append(button)
}
for i in 0..<4{
button.addTarget(self, action: selectors[i], for: .touchUpInside)
}
In the second loop, you do not initialize the button variable, so this is always the fourth button..
Better join this code in only one loop like so:
for i in 0..<4{
button = Button()
button.setTitle(buttonNames[i], for: .normal)
stacView.addArrangedSubview(button)
buttons.append(button)
button.addTarget(self, action: selectors[i], for: .touchUpInside)
}
Beyond this solution some advices to your coding style:
for convenience and better readability, function names and variable names should start with a lower letter
declare your variables in the smallest possible scope.
button, buttonNames and selectors are only used in ButtonFunction(), so these should be declared there.
declaration of button should in fact be in the for loop only. This way, the compiler would have told you, that button is unknown in your second loop and you would have seen the problem on your own ;)

Related

How to create action for UIButton in UIKit

I just created a UIButton and I want to do some action when I click on it i don't know how to do it , here is my way to just create uibutton only !!!:
lazy var test: UIButton = {
let test = UIButton()
test.translatesAutoresizingMaskIntoConstraints = false
test.setTitle("See More Answers", for: .normal)
test.setTitleColor(.systemBlue, for: .normal)
return seeMoreBtn
}()
The modern way is to add the action as a UIAction.
lazy var test: UIButton = {
let test = UIButton()
test.translatesAutoresizingMaskIntoConstraints = false
test.setTitle("See More Answers", for: .normal)
test.setTitleColor(.systemBlue, for: .normal)
let action = UIAction { action in
print("howdy!")
}
test.addAction(action, for: .touchUpInside)
return test
}()
Nicer syntax can be achieved through an extension, as I demonstrate here.
lazy var test: UIButton = {
let test = UIButton()
test.translatesAutoresizingMaskIntoConstraints = false
test.setTitle("See More Answers", for: .normal)
test.setTitleColor(.systemBlue, for: .normal)
test.addTarget(self, action: #selector(self.buttonPressedAction), for: .touchUpInside) // add target
return seeMoreBtn
}()
#objc func buttonPressedAction() {
//This function will get called when u press the button.
//include here what u want to do.
}
#objc func buttonAction() {
print("Button Tapped")
}
test.addTarget(self, action: #selector(buttonAction(_:)), for: .touchUpInside)
I have given the example for create the custom button and the custom label and set constraint in coding. The below code also contains the programmatically button action.
import UIKit
class ViewController: UIViewController {
let button = UIButton(frame: CGRect(x: 100,y: 400,width: 200,height: 60))
var label = UILabel(frame: CGRect(x: 100, y: 200, width: 200, height: 60))
var count : Int = 0
override func viewDidLoad() {
super.viewDidLoad()
button.setTitle("Click Button",for: .normal)
button.backgroundColor = UIColor.blue
button.setTitleColor(.white, for: .normal)
button.addTarget(self,action: #selector(buttonAction),for: .touchUpInside)
label.font = .systemFont(ofSize: 50)
label.backgroundColor = UIColor.gray
label.textAlignment = .center
self.view.addSubview(button)
self.view.addSubview(label)
}
#objc
func buttonAction() {
self.count += 1
self.label.text = "\(count)"
}
}
Output :-
Value of label increases when the button is click.

Trying to create method to access the buttons when pressed on swift?

import UIKit
import SpriteKit
import GameplayKit
struct Question {
var Question : String!
var Answers : [String]!
var AnswerNumber : Int!
}
class LevelOne: SKScene {
var button = Button()
var buttons = [Button]()
let Question_met = UILabel(frame: CGRect(x: 0.3, y: 0.3, width: 40, height: 21))
var Questions = [Question]()
var QNumber = Int()
var buttonNames = [""]
override func didMove(to view: SKView) {
let background = SKSpriteNode(imageNamed: "background")
background.position = CGPoint(x: self.size.width/2, y: self.size.height/2)
background.zPosition = 0
self.addChild(background)
QuestionFunction()
ButtonFuction()
PickQuestion()
}
#objc func QuestionFunction(){
Questions = [Question(Question: "What is a Car ?", Answers: ["Bat","Cat","Vehicle","Pat"], AnswerNumber: 3),
Question(Question: "What is a plane ?", Answers: ["Bat","Aircraft","Cat","Pat"], AnswerNumber: 2),
Question(Question: "What is a ant ?", Answers: ["Bat","Cat","Vegetable","Insect"], AnswerNumber: 4),
Question(Question: "What is a Apple ?", Answers: ["Bat","Cat","Fruit","Pat"], AnswerNumber: 3),]
Question_met.frame = CGRect(x: 330, y: 70, width: 200, height: 21)
Question_met.backgroundColor = UIColor.orange
Question_met.textColor = UIColor.white
Question_met.textAlignment = NSTextAlignment.center
Question_met.text = "What caused Global Warming ?"
self.view?.addSubview(Question_met)
}
#objc func ButtonFuction(){
let stacView = UIStackView()
stacView.spacing = 12
stacView.distribution = .fillEqually
stacView.axis = .horizontal
stacView.translatesAutoresizingMaskIntoConstraints = false
view!.addSubview(stacView)
buttonNames = ["One","Two","Three","Four"]
for name in buttonNames {
button = Button()
button.setTitle(name, for: .normal)
stacView.addArrangedSubview(button)
buttons.append(button)
}
NSLayoutConstraint.activate([stacView.centerXAnchor.constraint(equalTo: view!.centerXAnchor),stacView.centerYAnchor.constraint(equalTo: view!.centerYAnchor),stacView.widthAnchor.constraint(equalToConstant: 350),stacView.heightAnchor.constraint(equalToConstant:70)])
}
#objc func PickQuestion(){
if Questions.count > 0{
QNumber = 0
Question_met.text = Questions[QNumber].Question
for i in 0..<buttons.count{
buttons[i].setTitle(Questions[QNumber].Answers[i], for: .normal)
}
Questions.remove(at: QNumber)
}
else {
print("Done!")
}
}
#objc func handleButton() {
print("")
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
}
}
I created a quiz based game and programmed my button manually but not sure how to create methods that would handle when the button is pressed.
Not sure entirely what you are asking for so going to state what I think you are asking.
You are simply asking on how to connect a button to action.
You're button is declared button = UIButton() in the loop then the action would be handleButton method declared below.
You can simply do addTarget(:) for the button.
button.addTarget(self, action:#selector(handleButton), for: .touchUpInside)
You can google Swift Classname, i.e. Swift UIButton to determine the methods for that class. For example inside UIButton, we can see there is a method identified as addTarget(_:action:for).
From Apple's Docs:
You connect a button to your action method using the addTarget(_:action:for:) method or by creating a connection in Interface Builder. The signature of an action method takes one of three forms, which are listed in Listing 1. Choose the form that provides the information that you need to respond to the button tap.
Edit:
OP decided to ask how to assign button functionality within a loop. To do this, you need a list of functions aka Selectors that you can reference.
let selectors:[Selector] = [#selector(handleButton1), #selector(handleButton2, #selector(handleButton3)]
for i in 0..<3 {
button.addTarget(self, action: selectors[i], for: .touchUpInside)
}

Created Buttons appear in other scenes within the Game

// Button class
class Button: UIButton {
override init(frame: CGRect){
super.init(frame: frame)
setup()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup(){
backgroundColor = #colorLiteral(red: 0.1215686277, green: 0.01176470611, blue: 0.4235294163, alpha: 1)
layer.cornerRadius = 12
layer.masksToBounds = false
translatesAutoresizingMaskIntoConstraints = false
}
}
// The Class where button object is being created
struct Question {
var Question : String!
var Answers : [String]!
var AnswerNumber : Int!
}
class LevelOne: SKScene {
var button = Button()
var buttons = [Button]()
let Question_met = UILabel(frame: CGRect(x: 0.3, y: 0.3, width: 40, height: 21))
var Questions = [Question]()
var QNumber = Int()
var buttonNames = [""]
var AnsNumber = Int()
let selectors:[Selector] = [#selector(handleButton1), #selector(handleButton2), #selector(handleButton3),#selector(handleButton4)]
override func didMove(to view: SKView) {
let background = SKSpriteNode(imageNamed: "background")
background.position = CGPoint(x: self.size.width/2, y: self.size.height/2)
background.zPosition = 0
self.addChild(background)
questionFunction()
buttonFuction()
pickQuestion()
}
#objc func questionFunction(){
Questions = [Question(Question: "What is a BMW ?", Answers: ["Bat","Cat","Vehicle","Pat"], AnswerNumber: 2),
Question(Question: "What is a Boeing ?", Answers: ["Bat","Aircraft","Cat","Pat"], AnswerNumber: 1),
Question(Question: "What is a Ant ?", Answers: ["Insect","Cat","Insect","Nate"], AnswerNumber: 2),
Question(Question: "What is a Apple ?", Answers: ["Fruit","Cat","bat","Pat"], AnswerNumber: 0),
Question(Question: "Where is london ?", Answers: ["UK","USA","France","Germany"], AnswerNumber: 0),
Question(Question: "Where is New York ?", Answers: ["Canada","USA","France","Germany"], AnswerNumber: 2),
Question(Question: "where is Berlin ?", Answers: ["UK","USA","Italy","Germany "], AnswerNumber: 3),
Question(Question: "Where is Toronto ?", Answers: ["India","Africa","Canada","Norway"], AnswerNumber: 2),
Question(Question: "Where is Rome ?", Answers: ["Japan","China","Italy","Ireland"], AnswerNumber: 2),
Question(Question: "where is Chennai ?", Answers: ["India","Brazil","Swiss","Germany"], AnswerNumber: 0),]
Question_met.frame = CGRect(x: 330, y: 70, width: 200, height: 21)
Question_met.backgroundColor = UIColor.orange
Question_met.textColor = UIColor.white
Question_met.textAlignment = NSTextAlignment.center
Question_met.text = "What caused Global Warming ?"
self.view?.addSubview(Question_met)
}
#objc func buttonFuction(){
let stacView = UIStackView()
stacView.spacing = 12
stacView.distribution = .fillEqually
stacView.axis = .horizontal
stacView.translatesAutoresizingMaskIntoConstraints = false
view!.addSubview(stacView)
buttonNames = ["One","Two","Three","Four"]
for i in 0..<4{
button = Button()
button.setTitle(buttonNames[i], for: .normal)
stacView.addArrangedSubview(button)
buttons.append(button)
button.addTarget(self, action: selectors[i], for: .touchUpInside)
}
NSLayoutConstraint.activate([stacView.centerXAnchor.constraint(equalTo: view!.centerXAnchor),stacView.centerYAnchor.constraint(equalTo: view!.centerYAnchor),stacView.widthAnchor.constraint(equalToConstant: 350),stacView.heightAnchor.constraint(equalToConstant:70)])
}
#objc func pickQuestion(){
if Questions.count > 0{
QNumber = 0
Question_met.text = Questions[QNumber].Question
AnsNumber = Questions[QNumber].AnswerNumber
for i in 0..<buttons.count{
buttons[i].setTitle(Questions[QNumber].Answers[i], for: .normal)
}
Questions.remove(at: QNumber)
}
else {
print("Done!")
let sceneToMoveTo = Instructions(size: self.size)
sceneToMoveTo.scaleMode = self.scaleMode
let myTransition = SKTransition.fade(withDuration: 0.5)
self.view!.presentScene(sceneToMoveTo, transition: myTransition)
}
}
#objc func handleButton1() {
if AnsNumber == 0 {
pickQuestion()
print("Correct!")
}
else {
print("You are Wrong!!!")
}
}
#objc func handleButton2(){
if AnsNumber == 1 {
pickQuestion()
print("Correct!")
}
else {
print("You are Wrong!!!")
}
}
#objc func handleButton3(){
if AnsNumber == 2 {
pickQuestion()
print("Correct!")
}
else {
print("You are Wrong!!!")
}
}
#objc func handleButton4(){
if AnsNumber == 3 {
pickQuestion()
print("Correct!")
}
else {
print("You are Wrong!!!")
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
}
}
I currently developing a game, which contains various levels and menu scenes. The current level created a question label and answer buttons and even after the level is complete and you navigate to another scene the buttons and questions remain on the scene no matter which scene you navigate too.
I was hoping to get a solution to only have the buttons and label to appear on the designated scene and don't appear in other scenes unless stated.
Thank you in advance.
I don't think you understand the ownership model here. The ViewController owns its view. The view owns the SKView and the SKView owns the SKScene. There is a back pointer from the SKScene to its SKView, and you are using that to add a UIKit StakcView to the Scene's parent view. Since UIKit sits on top of the SKScene, your button is always visible. The correct architecture here is that the view should add and manage its own subviews. Whenever it loads a new SKScene it should determine what UI that scene needs and then hide any UI that should no be shown. You can do this by just setting .isHidden on the relevant views.

How do I prevent one UIView from being hidden by another UIView?

I'm creating a custom, reusable segmented controller using UIViews and I'm having a problem with overlapping views. It currently looks like this:
You can see that the blue selector is under the buttons but I want it to sit at the bottom and be four pixels high. To do this, I have:
let numberOfButtons = CGFloat(buttonTitles.count)
let selectorWidth = frame.width / numberOfButtons
let selectorYPosition = frame.height - 3 <--- This cause it to be hidden behind the button
selector = UIView(frame: CGRect(x: 0, y: selectorYPosition, width: selectorWidth, height: 4))
selector.layer.cornerRadius = 0
selector.backgroundColor = selectorColor
addSubview(selector)
bringSubviewToFront(selector) <--- I thought this would work but it does nothing
which results in the selector UIView being hidden behind the segment UIView (I have the Y position set to - 3 so you can see how it's being covered up. I actually want it to be - 4, but that makes it disappear entirely):
I thought using bringSubviewToFront() would bring it in front of the segment UIView but it doesn't seem to do anything. I've looked through Apple View Programming Guide and lots of SO threads but can't find an answer.
Can anybody help me see what I'm missing?
Full code:
class CustomSegmentedControl: UIControl {
var buttons = [UIButton]()
var selector: UIView!
var selectedButtonIndex = 0
var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
var borderColor: UIColor = UIColor.black {
didSet {
layer.borderColor = borderColor.cgColor
}
}
var separatorBorderColor: UIColor = UIColor.lightGray {
didSet {
}
}
var commaSeparatedTitles: String = "" {
didSet {
updateView()
}
}
var textColor: UIColor = .lightGray {
didSet {
updateView()
}
}
var selectorColor: UIColor = .blue {
didSet {
updateView()
}
}
var selectorTextColor: UIColor = .black {
didSet {
updateView()
}
}
func updateView() {
buttons.removeAll()
subviews.forEach { $0.removeFromSuperview() }
// create buttons
let buttonTitles = commaSeparatedTitles.components(separatedBy: ",")
for buttonTitle in buttonTitles {
let button = UIButton(type: .system)
button.setTitle(buttonTitle, for: .normal)
button.setTitleColor(textColor, for: .normal)
button.backgroundColor = UIColor.white
button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
buttons.append(button)
}
// make first button selected
buttons[0].setTitleColor(selectorTextColor, for: .normal)
let numberOfButtons = CGFloat(buttonTitles.count)
let selectorWidth = frame.width / numberOfButtons
let selectorYPosition = frame.height - 3
selector = UIView(frame: CGRect(x: 0, y: selectorYPosition, width: selectorWidth, height: 4))
selector.layer.cornerRadius = 0
selector.backgroundColor = selectorColor
addSubview(selector)
bringSubviewToFront(selector)
let stackView = UIStackView(arrangedSubviews: buttons)
stackView.axis = .horizontal
stackView.alignment = .fill
stackView.distribution = .fillEqually
addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
stackView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
stackView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
}
#objc func buttonTapped(button: UIButton) {
for (buttonIndex, btn) in buttons.enumerated() {
btn.setTitleColor(textColor, for: .normal)
if btn == button {
let numberOfButtons = CGFloat(buttons.count)
let selectorStartPosition = frame.width / numberOfButtons * CGFloat(buttonIndex)
UIView.animate(withDuration: 0.3, animations: { self.selector.frame.origin.x = selectorStartPosition })
btn.setTitleColor(selectorTextColor, for: .normal)
}
}
sendActions(for: .valueChanged)
}
}
You are covering up your selector with the stackView.
You need to do:
bringSubviewToFront(selector)
after you have added all of the views. Move that line to the bottom of updateView().

Text on UIButton not updating SWIFT

I am making an app in Swift on which all elements are added programatically.
//This code is inside of viewDidLoad function
makeButtonWithName(button: answer0B, title: "0", font:
"HelveticaNeue", fontSize: resetHeight, frame: CGRect(x:width/2 -
viewWidth/2, y: firstViewY, width: viewWidth, height: viewHeight),
selector: #selector(self.answer0(_:)))
makeButtonWithName(button: answer1B, title: "0", font: "HelveticaNeue",
fontSize: resetHeight, frame: CGRect(x:width/2 - viewWidth/2, y:
secondViewY, width: viewWidth, height: viewHeight), selector:
#selector(self.answer1(_:)))
makeButtonWithName(button: answer2B, title: "0", font:
"HelveticaNeue", fontSize: resetHeight, frame: CGRect(x:width/2 -
viewWidth/2, y: thirdViewY, width: viewWidth, height: viewHeight),
selector: #selector(self.answer2(_:)))
makeButtonWithName(button: answer3B, title: "0", font:
"HelveticaNeue", fontSize: resetHeight, frame: CGRect(x:width/2 -
viewWidth/2, y: fourthViewY, width: viewWidth, height: viewHeight),
selector: #selector(self.answer3(_:)))
firstNumber = Int(arc4random_uniform(9))
secondNumber = Int(arc4random_uniform(9))
incorrectAnswer1 = Int(arc4random_uniform(18))
incorrectAnswer2 = Int(arc4random_uniform(18))
incorrectAnswer3 = Int(arc4random_uniform(18))
timer.invalidate()
seconds = 31
runTimer()
randomNumbers()
//End viewDidLoad function
func answer0(_ sender: UIButton!){
let a:Int? = Int((answer0B.titleLabel?.text)!)
if a == answerNumber{
correctIncorrectLabel.text = "Correct"
correctIncorrectLabel.textColor = UIColor.green
correctNumber += 1
}
else{
correctIncorrectLabel.text = "Incorrect"
correctIncorrectLabel.textColor = UIColor.red
}
randomNumbers()
}
func answer1(_ sender: UIButton!){
let b:Int? = Int((answer1B.titleLabel?.text)!)
if b == answerNumber{
correctIncorrectLabel.text = "Correct"
correctIncorrectLabel.textColor = UIColor.green
correctNumber += 1
}
else{
correctIncorrectLabel.text = "Incorrect"
correctIncorrectLabel.textColor = UIColor.red
}
randomNumbers()
}
func answer2(_ sender: UIButton!){
let c:Int? = Int((answer2B.titleLabel?.text)!)
if c == answerNumber{
correctIncorrectLabel.text = "Correct"
correctIncorrectLabel.textColor = UIColor.green
correctNumber += 1
}
else{
correctIncorrectLabel.text = "Incorrect"
correctIncorrectLabel.textColor = UIColor.red
}
randomNumbers()
}
func answer3(_ sender: UIButton!){
let d:Int? = Int((answer3B.titleLabel?.text)!)
if d == answerNumber{
correctIncorrectLabel.text = "Correct"
correctIncorrectLabel.textColor = UIColor.green
correctNumber += 1
}
else{
correctIncorrectLabel.text = "Incorrect"
correctIncorrectLabel.textColor = UIColor.red
}
randomNumbers()
printProblem()
}
func randomNumbers(){
firstNumber = Int(arc4random_uniform(9))
secondNumber = Int(arc4random_uniform(9))
answerNumber = firstNumber + secondNumber
printProblem()
randomButton = Int(arc4random_uniform(4))
incorrectAnswer1 = Int(arc4random_uniform(18))
incorrectAnswer2 = Int(arc4random_uniform(18))
incorrectAnswer3 = Int(arc4random_uniform(18))
showTextOnButton()
totalCorrect.text = "Total Correct: \(correctNumber)"
}
func showTextOnButton(){
if randomButton == 0 {
answer0B.setTitle("\(answerNumber)", for: .normal)
answer1B.setTitle("\(incorrectAnswer1)", for: .normal)
answer2B.setTitle("\(incorrectAnswer2)", for: .normal)
answer3B.setTitle("\(incorrectAnswer3)", for: .normal)
}
if randomButton == 1 {
answer1B.setTitle("\(answerNumber)", for: .normal)
answer0B.setTitle("\(incorrectAnswer1)", for: .normal)
answer2B.setTitle("\(incorrectAnswer2)", for: .normal)
answer3B.setTitle("\(incorrectAnswer3)", for: .normal)
}
if randomButton == 2 {
answer1B.setTitle("\(answerNumber)", for: .normal)
answer2B.setTitle("\(incorrectAnswer1)", for: .normal)
answer0B.setTitle("\(incorrectAnswer2)", for: .normal)
answer3B.setTitle("\(incorrectAnswer3)", for: .normal)
}
if randomButton == 3 {
answer1B.setTitle("\(answerNumber)", for: .normal)
answer2B.setTitle("\(incorrectAnswer1)", for: .normal)
answer3B.setTitle("\(incorrectAnswer2)", for: .normal)
answer0B.setTitle("\(incorrectAnswer3)", for: .normal)
}
}
func printProblem(){
questionLabel.text = "\(firstNumber) + \(secondNumber)"
}
func makeButtonWithName(button: UIButton,title: String, font: String, fontSize: Int, frame: CGRect, selector: Selector) {
let button = UIButton(type: UIButtonType.custom)
button.setTitle(title, for: .normal)
button.frame = frame
button.setTitleColor(UIColor.white, for: .normal)
button.titleLabel?.font = UIFont(name: font, size: CGFloat(fontSize))
button.addTarget(self, action: selector, for: .touchUpInside)
self.view.addSubview(button)
}
These 4 buttons have text. When you click each of these, text on the buttons is not changing. The functions are using set title to update the text on the buttons, but for every run of the app the buttons do their function but the text on them remains at 0.
Okay... so many codes. So basically, to change the button.text, use
button.setTitle("new text", for: .normal)
Also, when user clicks on the button,first thing you maybe want to disable it by:
button.isEnable = false
Then after click action, enable it again
button.isEnable = true
This is because it may cause unexpected error when user intentionally/unintentionally multi click on that button.