What's wrong with my Swift function? - swift

I'm trying to make a dice roll game and I'm having issues getting certain rolls to show up. Currently it's incomplete, but my current rolls I've written code for aren't showing up properly. i.e. rolling a 4 presents a 3. I understand I need to refactor and I apologize for that abomination that is my function.
edit : It is incomplete at the moment... so I haven't added scenarios for the other rolls.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var one: UIView!
#IBOutlet weak var two: UIView!
#IBOutlet weak var three: UIView!
#IBOutlet weak var four: UIView!
#IBOutlet weak var five: UIView!
#IBOutlet weak var six: UIView!
#IBOutlet weak var seven: UIView!
#IBOutlet weak var labelOne: UILabel!
#IBOutlet weak var labelTwo: UILabel!
#IBOutlet weak var labelThree: UILabel!
#IBOutlet weak var labelFour: UILabel!
#IBOutlet weak var labelFive: UILabel!
#IBOutlet weak var labelSix: UILabel!
override func viewDidLoad() {
labelOne.isHidden = true
labelTwo.isHidden = true
labelThree.isHidden = true
labelFour.isHidden = true
labelFive.isHidden = true
labelSix.isHidden = true
one.isHidden = true
two.isHidden = true
three.isHidden = true
four.isHidden = true
five.isHidden = true
six.isHidden = true
seven.isHidden = true
super.viewDidLoad()
}
// Rearrange dice depending on what is rolled.
func rearrangeDie(){
if randomDiceRoll() == 1 {
six.isHidden = false
} else if six.isHidden == false {
six.isHidden = true }
if randomDiceRoll() == 2 {
one.isHidden = false
seven.isHidden = false }
else if one.isHidden == false &&
seven.isHidden == false {
self.one.isHidden = true
self.seven.isHidden = true
}
if randomDiceRoll() == 3 {
one.isHidden = false
six.isHidden = false
seven.isHidden = false }
else if one.isHidden == false && six.isHidden == false && seven.isHidden == false {
one.isHidden = true
six.isHidden = true
seven.isHidden = true
}
}
// Reveal labels as you roll
func textToLabel(roll:intmax_t) {
let diceScore = String(roll)
if labelOne.isHidden == true {
labelOne.text = diceScore
labelOne.isHidden = false
}
}
#IBAction func dice(_ sender: AnyObject) {
}
#IBAction func dieButtonTapped(_ sender: AnyObject) {
randomDiceRoll()
rearrangeDie()
print(randomDiceRoll())
}
// Returns back a random Int (1, 2, 3, 4, 5, or 6)
func randomDiceRoll() -> Int {
return Int(arc4random_uniform(6) + 1)
}
}

To many if statements in your code make it hard to read. Your sample is not complete and so is probably your question. Therefore I can just assume the following:
You want to display the dice roll as "eyes" or "dots"
Each dot is a UIView
Numbering is from top left to bottom, the center dot is number 7
So heres my suggested code:
func rearrangeDie(){
let roll = randomDiceRoll()
//1x2
//374
//5x6
//One is visible for 2, 3, 4, 5 and 6
//oxx
//xxx
//xxx
one.isHidden = roll == 1
//Two is visible for 4, 5 and 6
//xxo
//xxx
//xxx
two.isHidden = roll == 1 || roll == 2 || roll == 3
//...
//Seven is visible for 1, 3 and 5
//xxx
//xox
//xxx
seven.isHidden = roll == 2 || roll == 4 || roll == 6
}

Related

deselectd other button when one button isSeleted

I have three button link together called tipChanged .
one button was seleted by default (10%)
I want to write some code to make one button isSeleted ,the other two will automatically deseleted .my code work but too wordy ,any easy way ?
below is my code ,thanks in advance.
import UIKit
class CalculatorViewController: UIViewController {
#IBOutlet weak var zeroPctButton: UIButton!
#IBOutlet weak var tenPctButton: UIButton!
#IBOutlet weak var twentyPctButton: UIButton!
#IBAction func tipChanged(_ sender: UIButton) {
let pctChoosed = sender.currentTitle
if pctChoosed == "0%"{
zeroPctButton.isSelected = true
tenPctButton.isSelected = false
twentyPctButton.isSelected = false
}else if pctChoosed == "10%"{
zeroPctButton.isSelected = false
tenPctButton.isSelected = true
twentyPctButton.isSelected = false
}else{
zeroPctButton.isSelected = false
tenPctButton.isSelected = false
twentyPctButton.isSelected = true
}
}
}
Remove the if statement and just set them all to false. Then just under where they are set to false set sender.isSelected = true and you should get the desired results.

switching image on timed event in swift

I am trying to switch the displayed image in an UIImageView to different images based on an timed event by defining the what image should be displayed by I and the app works but when the timer gets to 5 the app crashes. if anyone can help me out then that would be great (also the Ad is the beginning of the image name so AD_1 - AD_4)
import UIKit
class ViewController: UIViewController {
//this is for declaring all the profile buttons
#IBOutlet weak var Icon_1: UIButton!
#IBOutlet weak var Icon_2: UIButton!
#IBOutlet weak var Icon_3: UIButton!
#IBOutlet weak var Icon_4: UIButton!
#IBOutlet weak var Icon_5: UIButton!
#IBOutlet weak var Icon_6: UIButton!
#IBOutlet weak var Icon_7: UIButton!
#IBOutlet weak var Icon_8: UIButton!
//this is used to swich the images
var i = Int(1)
let timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(fire), userInfo: nil, repeats: false)
//this is for the view
#IBOutlet weak var ad_view: UIView!
//this is for when the user swipes left
#IBAction func Icon_Swipe_Left(_ sender: Any) {
Icon_1.isHidden = true
Icon_2.isHidden = true
Icon_3.isHidden = true
Icon_4.isHidden = true
Icon_5.isHidden = false
Icon_6.isHidden = false
Icon_7.isHidden = false
Icon_8.isHidden = false
}
//this is when the user swipes right
#IBAction func Icon_Swipe_Right(_ sender: Any) {
Icon_1.isHidden = false
Icon_2.isHidden = false
Icon_3.isHidden = false
Icon_4.isHidden = false
Icon_5.isHidden = true
Icon_6.isHidden = true
Icon_7.isHidden = true
Icon_8.isHidden = true
}
// this is for decareing the image frame for the adds
#IBOutlet weak var Ad_Frame: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//this is for showing the fist set of icons
Icon_1.isHidden = false
Icon_2.isHidden = false
Icon_3.isHidden = false
Icon_4.isHidden = false
//this is for hideing the second set of icons
Icon_5.isHidden = true
Icon_6.isHidden = true
Icon_7.isHidden = true
Icon_8.isHidden = true
self.Ad_Frame.image = UIImage(named: "AD_\(i)")
}
#objc func fire()
{
i += 1
self.Ad_Frame.image = UIImage(named: "AD_\(i)")
}
}
Two things:
1: you say you have images AD_1 - AD_4 - that's only four images, so it won't cope with the fifth! I'm assuming you mean AD_1 - AD_5
2: More importantly, you start with i = 1, and then add 1 before trying to display the image, so you're actually trying to display images 2...6.
Increment i after displaying the image, not before
Change fire so that it starts over once 5 is reached
#objc func fire() {
self.Ad_Frame.image = UIImage(named: "AD_\(i)")
i += 1
if i > 4 { i = 1 }
}
Off-topic but I would recommend renaming i to something more readable like counter for instance. Single letter variables are not recommended apart from in for loops. Also when declaring it you don't need to call Int(...) but assign the value directly instead, var counter = 1

How to display a certain view depending on random number generation in swift?

I am following a tutorial, this is the repo on git
I have 7 views, that represent the die. And 6 labels, that show the random number each time I press the dieButtonTapped() button. When I press the button, first label appears with the random number generated, which is good, but I can't get the appropriate view to show up. So, if the random number is 5, label shows up with the number 5 in it, and 5 views out of 7 should show up, representing the die.
What it is doing now is that it shows random views that do not match the random number showed on the label.
Please help me correct func rearrangeDie() function to match what func updateScore(roll: Int) is returning.
Thank you !
Here is my code:
class ViewController: UIViewController {
#IBOutlet weak var view1: UIView!
#IBOutlet weak var view2: UIView!
#IBOutlet weak var view3: UIView!
#IBOutlet weak var view4: UIView!
#IBOutlet weak var view5: UIView!
#IBOutlet weak var view6: UIView!
#IBOutlet weak var view7: UIView!
#IBOutlet weak var label1: UILabel!
#IBOutlet weak var label2: UILabel!
#IBOutlet weak var label3: UILabel!
#IBOutlet weak var label4: UILabel!
#IBOutlet weak var label5: UILabel!
#IBOutlet weak var label6: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
view1.isHidden = true
view2.isHidden = true
view3.isHidden = true
view4.isHidden = true
view5.isHidden = true
view6.isHidden = true
view7.isHidden = true
label1.isHidden = true
label2.isHidden = true
label3.isHidden = true
label4.isHidden = true
label5.isHidden = true
label6.isHidden = true
}
#IBAction func dieButtonTapped(_ sender: AnyObject) {
rearrangeDie()
updateScore(roll: randomDiceRoll())
}
// Returns back a random Int (1, 2, 3, 4, 5, or 6)
func randomDiceRoll() -> Int {
return Int(arc4random_uniform(6) + 1)
}
func rearrangeDie() {
if randomDiceRoll() == 1 {
view7.isHidden = false
}
else if randomDiceRoll() == 2 {
view2.isHidden = false
view5.isHidden = false
}
else if randomDiceRoll() == 3 {
view2.isHidden = false
view7.isHidden = false
view5.isHidden = false
}
else if randomDiceRoll() == 4 {
view1.isHidden = false
view2.isHidden = false
view5.isHidden = false
view6.isHidden = false
}
else if randomDiceRoll() == 5 {
view1.isHidden = false
view2.isHidden = false
view5.isHidden = false
view6.isHidden = false
view7.isHidden = false
}
else if randomDiceRoll() == 6 {
view1.isHidden = false
view2.isHidden = false
view3.isHidden = false
view4.isHidden = false
view5.isHidden = false
view6.isHidden = false
}
}
func updateScore(roll: Int) {
let diceScore = String(roll)
if label1.isHidden {
label1.text = diceScore
label1.isHidden = false
}
else if label2.isHidden {
label2.text = diceScore
label2.isHidden = false
}
else if label3.isHidden {
label3.text = diceScore
label3.isHidden = false
}
else if label4.isHidden {
label4.text = diceScore
label4.isHidden = false
}
else if label5.isHidden {
label5.text = diceScore
label5.isHidden = false
}
else if label6.isHidden {
label6.text = diceScore
label6.isHidden = false
}
else {
viewDidLoad()
}
}
}
You are basically generating a new random number each time you call randomDiceRoll(). Store it in a variable and access it throughout the if statements.
I would also strongly suggest a programatically created layout and a serious refactoring.
func rearrangeDie() {
let randomDiceRoll = randomDiceRoll()
if randomDiceRoll == 1 {
view7.isHidden = false
}
else if randomDiceRoll == 2 {
view2.isHidden = false
view5.isHidden = false
}
else if randomDiceRoll == 3 {
view2.isHidden = false
view7.isHidden = false
view5.isHidden = false
}
else if randomDiceRoll == 4 {
view1.isHidden = false
view2.isHidden = false
view5.isHidden = false
view6.isHidden = false
}
else if randomDiceRoll == 5 {
view1.isHidden = false
view2.isHidden = false
view5.isHidden = false
view6.isHidden = false
view7.isHidden = false
}
else if randomDiceRoll == 6 {
view1.isHidden = false
view2.isHidden = false
view3.isHidden = false
view4.isHidden = false
view5.isHidden = false
view6.isHidden = false
}
}
#the4Kman is correct in stating that calling the randomDiceRoll() will generate a new random number every time which leads to the problem you are facing. What you need instead, is to merge your rearrangeDie() and updateScore() methods into one. Also, as #nanothread59 suggested, you should use IBOutletCollections.
You should declare your collections like this
//Notice that you cannot make them "weak" properties
#IBOutlet var views: Array<UIView>!
#IBOutlet var labels: Array<UILabel>!
Then give each of your view and label a tag from 1-7 in storyboard and connect them to their respective outletCollections. Once it is setup, you can merge your methods into one like this
func update() {
//Hide all Views and Labels
for item in views {
item.isHidden = true
}
for item in labels {
item.isHidden = true
}
//Get Random Value
let random = randomDiceRoll()
//UPDATE YOUR VIEWS' AND LABELS' HIDDEN PROPERTY AND VALUES HERE BASED ON THE RANDOM VALUE
//To access a particular view or label, you'll do something like this
for item in views {
if item.tag == {whatever} {
//DO SOMETHING
}
}
//Repeat the above loop for labels as well
}
P.S. With IBOutletCollections, your viewDidLoad will also change like this
override func viewDidLoad() {
super.viewDidLoad()
//Hide all Views and Labels
for item in views {
item.isHidden = true
}
for item in labels {
item.isHidden = true
}
}

enable NSButton if NSTextfield is not empty

I am creating a OSX app and would like to enable a button when all textfield are filled. But do not have much experience with osx app as there seem to be some difference from ios.
This is what I have tried.
override func viewDidLoad() {
super.viewDidLoad()
btnCalculate.enabled = false
}
override func controlTextDidChange(obj: NSNotification) {
if panelsWideTextField.stringValue.isEmpty {
btnCalculate.enabled = false
} else {
btnCalculate.enabled = true
}
}
Hope someone has a good tip for me :-)
EDIT:
Complete code.
import Cocoa
//import AppKit
class ViewController: NSViewController, NSTextFieldDelegate {
#IBOutlet weak var panelHightTextField: NSTextField!
#IBOutlet weak var panelWidthTextField: NSTextField!
#IBOutlet weak var panelPitchTextField: NSTextField!
#IBOutlet weak var panelsHighTextField: NSTextField!
#IBOutlet weak var panelsWideTextField: NSTextField!
#IBOutlet weak var resWidthLabel: NSTextField!
#IBOutlet weak var resHightLabel: NSTextField!
#IBOutlet weak var lblScreenWidth: NSTextField!
#IBOutlet weak var lblScreenHight: NSTextField!
#IBOutlet weak var lblScreenArea: NSTextField!
#IBOutlet weak var btnCalculate: NSButton!
#IBOutlet weak var lblAmountPanels: NSTextField!
var panelHight = ""
var panelWidth = ""
var panelPitch = ""
var panelsHigh = ""
var panelsWidth = ""
var resWidth : Float = 0
var resHigh : Float = 0
var screenHight : Float = 0
var screenWidth : Float = 0
var screenArea : Float = 0
var ammountPanels : Float = 0
override func viewDidLoad() {
super.viewDidLoad()
btnCalculate.enabled = false
}
override func controlTextDidChange(obj: NSNotification) {
if panelsWideTextField.stringValue.isEmpty {
btnCalculate.enabled = true
} else {
btnCalculate.enabled = false
}
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
#IBAction func calculateResButton(sender: AnyObject) {
takeUserData()
calculatehight()
calculatewidth()
calculateArea()
calculateAmountPanels()
}
func takeUserData(){
panelHight = panelHightTextField.stringValue
panelWidth = panelWidthTextField.stringValue
panelPitch = panelPitchTextField.stringValue
panelsHigh = panelsHighTextField.stringValue
panelsWidth = panelsWideTextField.stringValue
}
// Calculating resolution and physical hight
func calculatehight(){
let fpanelHight = Float(panelHight)
let fpanelPitch = Float(panelPitch)
let fpanelsHigh = Float(panelsHigh)
resHigh = fpanelHight! * fpanelsHigh! / fpanelPitch!
screenHight = fpanelHight! * fpanelsHigh! / 1_000
printText()
}
// Calculating resolution and physical width
func calculatewidth(){
let fpanelWidth = Float(panelWidth)
let fpanelPitch = Float(panelPitch)
let fpanelsWidth = Float(panelsWidth)
resWidth = fpanelWidth!*fpanelsWidth!/fpanelPitch!
screenWidth = fpanelWidth!*fpanelsWidth! / 1_000
printText()
}
// Calculating sqm of LED screen
func calculateArea(){
let fpanelHight = Float(panelHight)
let fpanelsHigh = Float(panelsHigh)
let fpanelWidth = Float(panelWidth)
let fpanelsWidth = Float(panelsWidth)
screenArea = (fpanelHight! * fpanelsHigh!) * (fpanelWidth! * fpanelsWidth!) / 1_000_000
printText()
}
// Calculating the amount of panels used.
func calculateAmountPanels(){
let fpanelsHigh = Float(panelsHigh)
let fpanelsWidth = Float(panelsWidth)
ammountPanels = (fpanelsWidth! * fpanelsHigh!)
printText()
}
// Outputting text to labels with correct format.
func printText(){
let formatResHigh = String(format: "%0.0f", resHigh)
let formatResWidth = String(format: "%0.0f", resWidth)
let formatScreenHight = String(format: "%0.2f", screenHight)
let formatScreenWidth = String(format: "%0.2f", screenWidth)
let formatScreenArea = String(format: "%0.0f", screenArea)
let formatAmmountPanels = String(format: "%0.0f", ammountPanels)
resHightLabel.stringValue = "\(formatResHigh)px"
resWidthLabel.stringValue = "\(formatResWidth)px"
lblScreenHight.stringValue = "\(formatScreenHight)m"
lblScreenWidth.stringValue = "\(formatScreenWidth)m"
lblScreenArea.stringValue = "\(formatScreenArea) sqm"
lblAmountPanels.stringValue = "\(formatAmmountPanels)"
}
}
I had the same problem but I found simple solution: checkbox can enable and disable NSButton.
import Cocoa
class ViewController: NSViewController {
#IBOutlet weak var btnCalculate: NSButton!
#IBOutlet weak var checkBox: NSButton!
override func viewDidLoad() {
super.viewDidLoad()
btnCalculate.enabled = false
checkBox.state = 0
}
#IBAction func checkAgree(sender: NSButton) {
if btnCalculate.stringValue.characters.count > 0 && checkBox.state == 1 {
btnCalculate.enabled = true
} else {
btnCalculate.enabled = false
}
}
}

Disable button in cocoa application OS X

I would like to have the submit button enabled once some fields on a form have been validated. Currently the preview function works great, preview button provides the validation I need. Working on Xcode 7 and swift 2. I would really appreciated if someone can point me in the right direction. Below is the code I currently have:
import Cocoa
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var projectFlag = false
var descriptionFlag = false
var releaseFlag = false
// Fields
#IBOutlet weak var projectNumberTextField:NSTextField!
#IBOutlet weak var projectDescriptionTextField:NSTextField!
#IBOutlet weak var releaseFolderNameTextField:NSTextField!
#IBOutlet weak var passwordTextField:NSTextField!
// Labels for preview
#IBOutlet weak var label1: NSTextField!
#IBOutlet weak var label2: NSTextField!
#IBOutlet weak var label3: NSTextField!
#IBOutlet weak var label4: NSTextField!
#IBOutlet weak var label5: NSTextField!
// Quit Button :: Quits the application
#IBAction func quitButton(sender: AnyObject) {
NSApplication.sharedApplication().terminate(self)
}
// Preview button behavior
#IBAction func previewButton(sender: AnyObject) {
// Project Number ::
let project = projectNumberTextField.stringValue
label1.stringValue = "\(project)"
if (label1.stringValue == "00-0000") {
label1.stringValue = "Project Number is not valid"
label1.textColor = NSColor.redColor()
projectFlag = false
} else {
label1.textColor = NSColor.blackColor()
projectFlag = true
}
// Project Description :: Name, 2016
let description = projectDescriptionTextField.stringValue
label2.stringValue = "\(description)"
if (label2.stringValue == "Name, 2016") {
label2.stringValue = "Enter a valid project description"
label2.textColor = NSColor.redColor()
descriptionFlag = false
} else {
label2.textColor = NSColor.blackColor()
descriptionFlag = true
}
// Folder Release Name :: RELEASE_NAME
let release = releaseFolderNameTextField.stringValue
label3.stringValue = "\(release)"
if (label3.stringValue == "RELEASE_NAME") {
label3.stringValue = "Enter a valid folder release name"
label3.textColor = NSColor.redColor()
releaseFlag = false
} else {
label3.textColor = NSColor.blackColor()
releaseFlag = true
}
// Password :: If needed
let password = passwordTextField.stringValue
label4.stringValue = "\(password)"
// Preview :: Code format for txt file
let preview = "\(project)|"+"\(description)|"+"\(release)|"+"\(password)/"
label5.stringValue = "\(preview)"
}
// Submit button behavior
#IBAction func submitButton(Sender: AnyObject) {
}
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}