I have a little problem but I can't figured out ...
I code a sort a Shutdown countdown and I need to re-use the variable name "x" in the following code :
#IBAction func valueChange(sender: NSSlider) {
let x = sender.intValue
valueofSlider.stringValue = "\(x)"
}
IBOutlet weak var countDown: NSTextField!
var starter = false;
#IBAction func startCountDown(sender: NSButton) {
starter = true
}
var trigger = 600 //here I put the value myself but i would like
var trigger = (x * 60) //to get the slider value in seconds
First create an Outlet for your slider and then a variable to hold its value. Assign the variable inside valueChanged and now you can use it wherever you want:
#IBOutlet var slider: UISlider!
var sliderValue: Float = 0
#IBAction func valueChanged(sender: AnyObject) {
sliderValue = slider.value
print(sliderValue)
}
Related
I couldn't figure out how to copy value of variable into another variable in Swift, an example code for this in python would be
def assignVariable():
x=1
y=x
return y
RESULT 1
When I did this it doesn't seem to work in Swift. Is there any solution to this or am I doing something wrong?
Edit: problem is at
var originalCount=countDown
it gave me Use of unresolved identifier 'countDown' but when I assign it literally it works. Here's my swift code
import Cocoa
class MainWindow: NSWindowController {
var hitCount = 0
var started:Bool = false
var timer = 10
var colorList: [NSColor] = [ NSColor.black,NSColor.blue,NSColor.brown,NSColor.cyan,NSColor.darkGray,NSColor.gray,NSColor.green,NSColor.lightGray,NSColor.magenta,NSColor.orange,NSColor.purple,NSColor.red,NSColor.white,NSColor.yellow]
#IBOutlet weak var button1: NSButton!
#IBOutlet weak var scrubber1: NSScrubber!
#IBOutlet weak var display: NSTextField!
override func windowDidLoad() {
super.windowDidLoad()
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}
var countdown=10
var originalCount=countDown
//(countdown,originalCount) = (10,10) //it works if i use this instead
func startGame(){
if(countDown>0 || started==true){
display.stringValue=String(countDown)
countDown-=1
let seconds = 1.0
DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
self.startGame()
}
}else{
display.stringValue="Done "+String(hitCount)+" Taps in " + String(originalCount) + "Tap to RESET"
started=false
countDown=10;
}
}
#IBAction func labelPress(_ sender: Any) {
display.stringValue="__RESET__"
hitCount=0
countDown=10
started=false
}
#IBAction func buttonPressed(_ sender: Any) {
if started==false{
startGame()
}
button1.bezelColor = colorList[Int.random(in: 0..<colorList.count)]
started=true
button1.title=String(hitCount)
hitCount+=1
}
}
You can't initialise one variable with another at the top level in your class. Looking at your code I don't think that originalCount needs to be a property, move it inside startGame() instead and make it a local variable and also use let since it isn't changing
var countdown=10
func startGame(){
let originalCount = countDown
if(countDown>0 || started==true){
...
}
I am trying to get a String value to a Float value from a NSPopUpButton.
E.g. I have 3 number selections. 50, 20, 10. When the user selects one of the numbers I would like a calculation made into a Float value.
I know this may be something very simple but I am new and I can't find anything on Stackoverflow. Any help would be appreciated. Here is an example of the code I have.
#IBOutlet weak var userInput: NSTextField!
#IBOutlet weak var result: NSTextField!
#IBOutlet weak var userMenuSelection: NSPopUpButton!
override func viewDidLoad() {
super.viewDidLoad()
userMenuSelection.removeAllItems()
userMenuSelection.addItems(withTitles: ["50", "20", "10"])
}
#IBAction func pushButtonforResult(_ sender: Any) {
/*
Not sure how to take the selected userMenuSelection and multiply it by the users input to get my result in a float.
E.g. look below. This of course does not work because the menu items are strings.
*/
result.floatValue = userMenuSelection * userInput.floatValue
}
Hope this makes sense to what I am asking.
As you see, your userMenuSelection has titles representing the Float values as String.
You can simply retrieve the selected title and convert it to Float:
#IBAction func pushButtonforResult(_ sender: Any) {
var selectedValue = Float(userMenuSelection.titleOfSelectedItem ?? "0") ?? 0.0
result.floatValue = selectedValue * userInput.floatValue
}
You can try
let arr = ["50", "20", "10"]
//
#IBAction func pushButtonforResult(_ sender: NSPopUpButton) {
let selectedValue = Float(arr[sender.selectedTag()])!
Result.floatValue = selectedValue * userInput.floatValue
// OR
let selectedValue = Float(sender.selectedItem!.title)!
result.floatValue = selectedValue * userInput.floatValue
}
i'm a fairly new programmer and i've just started on Xcode. Atm i am trying to make a calculator that can calculate the total volume from 3 input values (Height, length & width) but i can't seem to make it calculate it. right now i am able to enter a value and click the button and then it crashes.
Thanks in advance!
here is my code:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
#IBOutlet weak var HeightInput: NSTextField!
#IBOutlet weak var LengthInput: NSTextField!
#IBOutlet weak var WidthInput: NSTextField!
#IBOutlet weak var Result: NSTextField!
#IBAction func Calculate(_ sender: Any) {
var height = Int(HeightInput.stringValue)
var width = Int(WidthInput.stringValue)
var length = Int(LengthInput.stringValue)
if height == 0
{
Result.stringValue = "Error"
}
else{
var result = width! * height! * length!
Result.stringValue = "the volume is: \(result)"
}
}
Try something like this.
#IBAction func Calculate(_ sender: Any) {
let height = Int(HeightInput.stringValue) ?? 0
let width = Int(WidthInput.stringValue) ?? 0
let length = Int(LengthInput.stringValue) ?? 0
let result = height * width * length
if result == 0 {
Result.stringValue = "Error"
else {
Result.stringValue = "The volume is: \(result)"
}
}
When converting your label value to an integer, it will return an optional (meaning it could be nil). When you are calculating your result, you are force-unwrapping these optionals with the !.
I recommend conditionally unwrapping these values. Using ?? meaning that if the value is nil, it will default to whatever you put after the ??.
i-m trying to learn how to code and working on my first ever app. it is some gym app. and i want to have a timer and a label to be changed after presing a button.
This is my code until now but i cant figure it out how to display the next label and the next timer to countdown after presing the button.
class _daysday1ViewController: UIViewController {
#IBOutlet weak var exerciseNameLabel: UILabel!
#IBOutlet weak var btnStart: UIButton!
#IBOutlet weak var exercisePicture: UIImageView!
#IBOutlet weak var exerciseDescriptionLabel: UILabel!
#IBOutlet weak var timerLabel: UILabel!
#IBAction func nextButtonTapped(sender: AnyObject) {
var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("update"), userInfo: nil, repeats: true)
count = countList[0]
}
var exerciseIndex = 0
var exerciseList = ["12 reps at 80% of capicity" , " 10 reps at 90%" , "7 to 10 reps at full capacity"]
var countList = [4 , 6 ,8]
var count = 1
override func viewDidLoad() {
super.viewDidLoad()
}
func update() {
if(count >= 0) {
timerLabel.text = String(count--)
self.btnStart.enabled = false
return
}
btnStart.enabled = true
exerciseDescriptionLabel.text = exerciseList[0]
}
`
Your timer will go away almost as soon as it's created, because you declared the timer var within the nextButtonTapped function. That function finishes quickly, and your timer goes away when it finishes.
To fix this, declare the timer var at the class level, the same place you declared the count var, like this:
var timer: NSTimer?
Declaring it as an optional (?) allows it be nil until the next button is tapped.
To create it, simply change the line of code in nextButtonTapped to begin with this:
self.timer = ...
Instead of this:
var timer = ...
In your func nextButtonTapped() method, you can include the code for this. The #IBAction will make this method fire every time the button is touched, so if you need variables to change with this action simple outline what you want to change between the {};
example:
var currentExercise = 0
#IBAction func nextButtonTapped() {
btnStart.textLabel.text = "New Text To Display"
currentExercise += 1
exerciseDescriptionLabel.text = exerciseList[currentExercise]
}
I am making an app where there is a football field and when you click on the Score Zone 7 points are added to the UILabel that marks score. But I have only been able to display a 7 once and if I click again the seven appears again; I want it to add 7 more to make a 14.
#IBAction func touchdownMD(sender: AnyObject) {
var pointsMD = Int()
scoreMD.text = "\(pointsMD + 7)"
}
#IBOutlet var scoreSH: UILabel!
When you initialize pointsMD inside of the touchdownMD: function, it starts from 0 whenever the function is called.
In order to fix this, you need to declare it at the class level. For example:
var pointsMD = Int() //initialize pointsMD at the class level
#IBAction func touchdownMD(sender: AnyObject){
pointsMD+=7 //add 7 to pointsMD
scoreMD.text = "\(pointsMD)"
}
That way, pointsMD will not reset whenever touchdownMD: is called, it will instead just increment as needed.
So, here's what your code could look like:
var pointsMD = Int()
#IBAction func touchdownMD(sender: AnyObject) {
pointsMD+=7
scoreMD.text = "\(pointsMD)"
}
#IBOutlet var scoreSH: UILabel!