I am making an app where a textfield input is shown on a label for the amount of time (in seconds) indicated on an other textfield. My app only runs when var seconds is set to an integer and not to the textfield input. When I set var seconds to the textfield input, I get the following error on the indicated lines of code: 'ViewController' does not have a member named 'seconds' Can anyone help? Thanks.
Here is all of my code, the lines of code with the error have //Error beside them:
class ViewController: UIViewController {
#IBOutlet weak var chronometre: UILabel!
#IBOutlet weak var prochainpointLabel: UILabel!
#IBOutlet weak var pointactuelLabel: UILabel!
#IBOutlet weak var point1Textfield: UITextField!
#IBOutlet weak var point1tempsTextfield: UITextField!
#IBOutlet weak var point2Textfield: UITextField!
#IBOutlet weak var point2tempsTextfield: UITextField!
var timer = NSTimer()
var seconds = point1tempsTextfield.text.toInt()
func subtractTime(dt:NSTimer){
seconds-- //Error
chronometre.text = "\(seconds)" //Error
if(seconds == 0) { //Error
seconds = point2tempsTextfield.text.toInt()
pointactuelLabel.text = point2Textfield.text
prochainpointLabel.text = nil
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func presenterButton(sender: AnyObject) {
pointactuelLabel.text = point1Textfield.text
prochainpointLabel.text = point2Textfield.text
chronometre.text = "\(seconds)" //Error
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: ("subtractTime:"), userInfo: nil, repeats: true)
}
}
Thank you for your help, I am very new to coding and really appreciate it!
Forget about using a timer to calculate time. You should use NSTimeInterval between two dates to measure elapsed time.
ElapsedTime
extension NSTimeInterval {
var time:String {
return String(format:"%02d:%02d", Int((self/60.0)%60), Int((self) % 60 ))
}
}
var startTime:NSTimeInterval = 0
var elapsedTime:NSTimeInterval = 0
startTime = NSDate().timeIntervalSinceReferenceDate // 446644854.4675
sleep(3) //
elapsedTime = NSDate().timeIntervalSinceReferenceDate - startTime // 3.005680024623871
println(elapsedTime.time) "00:03"
// applying this concept to your code would look like this:
class ViewController: UIViewController {
#IBOutlet weak var chronometre: UILabel!
#IBOutlet weak var prochainpointLabel: UILabel!
#IBOutlet weak var pointactuelLabel: UILabel!
#IBOutlet weak var point1Textfield: UITextField!
#IBOutlet weak var point1tempsTextfield: UITextField!
#IBOutlet weak var point2Textfield: UITextField!
#IBOutlet weak var point2tempsTextfield: UITextField!
var timer = NSTimer()
var startTime:NSTimeInterval = 0
func updateTime(){
chronometre.text = (NSDate().timeIntervalSinceReferenceDate - startTime).time
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func presenterButton(sender: AnyObject) {
pointactuelLabel.text = point1Textfield.text
prochainpointLabel.text = point2Textfield.text
timer = NSTimer.scheduledTimerWithTimeInterval(1/10, target: self, selector: ("updateTime:"), userInfo: nil, repeats: true)
startTime = NSDate().timeIntervalSinceReferenceDate
}
}
Related
I got an issue.
I want to set a timer that could disable the 6 large buttons of my ViewController2.
For example : Until the timer reach 100, it's not possible to click on the buttons Clue1Button,Clue2Button,Clue3Button,Clue4Button,Clue5Button,Clue6Button
Until the timer reach 200, it's not possible to click on the buttons 2,3,4,5,6 ...
How should I do it ? I tried several times, but I failed each time. Thanks for your help
Code of my ViewController2 :
// ViewController2.swift
// PROJET X
//
// Created by Alexis Decloedt on 22/12/2019.
// Copyright © 2019 Alexis Decloedt. All rights reserved.
//
import UIKit
class ViewController2: UIViewController {
#IBOutlet weak var Clue1Button: UIButton!
#IBOutlet weak var Clue2Button: UIButton!
#IBOutlet weak var Clue3Button: UIButton!
#IBOutlet weak var Clue4Button: UIButton!
#IBOutlet weak var Clue5Button: UIButton!
#IBOutlet weak var Clue6Button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func ChestButton(_ sender: Any) {
dismiss(animated: false, completion: nil)
}
}
//
// ViewController2.swift
// PROJET X
//
// Created by Alexis Decloedt on 22/12/2019.
// Copyright © 2019 Alexis Decloedt. All rights reserved.
//
import UIKit
var currentCount : Int?
var maxCount : Int?
var mytimer : Timer?
let ValeurStock = "ValeurStock"
class ViewController2: UIViewController {
#IBOutlet weak var Clue1Button: UIButton!
#IBOutlet weak var Clue2Button: UIButton!
#IBOutlet weak var Clue3Button: UIButton!
#IBOutlet weak var Clue4Button: UIButton!
#IBOutlet weak var Clue5Button: UIButton!
#IBOutlet weak var Clue6Button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
currentCount = 0
self.mytimer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(increase), userInfo: nil, repeats: true)
}
#IBAction func ChestButton(_ sender: Any) {
dismiss(animated: false, completion: nil)
}
func increase() {
currentCount! += 1
}
func buttonStatus() {
if currentCount ?? <#default value#> >= 100 {
//I'm stuck ?? How to continue ?
}
}
}
Try to make my button disable/enable
What you may want to do is:
//Add variable that will count how many times Timer was repeated.
var timerCount = 0
//Create timer
Timer.scheduledTimer(withTimeInterval: 100, repeats: true) { t in
//After first 100 sec passed, timer will get triggered and enable the buttons you want.
button1.isEnabled = true
button2.isEnabled = true
//After another 100 passed, timer will enable other buttons
if timerCount == 1 {
button3.isEnabled = true
button4.isEnabled = true
t.invalidate()
}
//Adds 1 to timer count
timerCount += 1
}
So I'm trying to program an "Mad Lib" themed app for a class I'm in but I keep getting a
EXC_BAD_INSTRUCTION
error when I hit the submit button. The other students in the class couldn't figure it out either. Please help me!
Here is my firstViewController.swift:
import UIKit
class ViewController: UIViewController
{
#IBOutlet weak var firstTextField: UITextField! //adjective
#IBOutlet weak var secondTextField: UITextField! //male name
#IBOutlet weak var thirdTextField: UITextField! //verb
#IBOutlet weak var fourthTextField: UITextField! //female name
#IBOutlet weak var fifthTextField: UITextField! //adjective
#IBOutlet weak var sixthTextField: UITextField! //athlete
#IBOutlet weak var seventhTextField: UITextField! //food
#IBOutlet weak var eighthTextField: UITextField! //restaurant name
var userInfo = myCustomClass()
override func viewDidLoad()
{
super.viewDidLoad()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
userInfo.adjectiveOne = firstTextField.text!
userInfo.maleName = secondTextField.text!
userInfo.verb = thirdTextField.text!
userInfo.femaleName = fourthTextField.text!
userInfo.adjectiveTwo = fifthTextField.text!
userInfo.athlete = sixthTextField.text!
userInfo.food = seventhTextField.text!
userInfo.restaurantName = eighthTextField.text!
let nextView = segue.destination as! secondViewController
nextView.passedObject = userInfo
}
}
Here is my secondViewController.swift:
import UIKit
class secondViewController: UIViewController
{
var passedObject = myCustomClass()
#IBOutlet weak var myFinishedProduct: UILabel!
override func viewDidLoad()
{
super.viewDidLoad()
myFinishedProduct.text = "There was once a \(passedObject.adjectiveOne) man /n \(passedObject.maleName). One day while he was \(passedObject.verb) he saw /n \(passedObject.femaleName), a rather \(passedObject.adjectiveTwo) woman. /n She was also a \(passedObject.athlete), and a very good /n one too. The two went to lunch together at \(passedObject.restaurantName) /n and ate some \(passedObject.food). After /n that they never crossed paths again."
}
}
Finally here is my NSOBject called "myCustomClass.swift":
import UIKit
class myCustomClass: NSObject
{
var adjectiveOne = ""
var maleName = ""
var verb = ""
var femaleName = ""
var adjectiveTwo = ""
var athlete = ""
var food = ""
var restaurantName = ""
}
Basically, `whatever the user enters into the eight text fields will be stored in myCustomClass when the submit button is pressed. From there, in the secondViewController it will put the eight inputs into the story and display it on a label.
Any help is appreciated, thank you!
Edit: The "Submit Button" is connected to the secondViewController on my storybook with the purpose of "show".
First View Controller
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var txtmobile: UITextField!
#IBOutlet weak var txtlname: UITextField!
#IBOutlet weak var txtfname: UITextField!
var ArrayStudent:[PassData] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func btnclick(_ sender: UIButton)
{
let objdata = PassData(fname: txtfname.text!, lname: txtlname.text!, mobile: txtmobile.text!)
ArrayStudent.append(objdata)
passdata()
}
func passdata()
{
let objstory = storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
objstory.Arradata1 = ArrayStudent
_ = self.navigationController?.pushViewController(objstory, animated: true)
}
}
Second View Controller
import UIKit
class SecondViewController: UIViewController {
#IBOutlet weak var lblmobile: UILabel!
#IBOutlet weak var lbllastname: UILabel!
#IBOutlet weak var lblname: UILabel!
var Arradata1:[PassData ] = []
override func viewDidLoad() {
super.viewDidLoad()
lblname.text = Arradata1.first?.StrFirstName
lbllastname.text = Arradata1.first?.StrLastName
lblmobile.text = Arradata1.first?.StrMobile
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
NSObject Class
import UIKit
class PassData: NSObject
{
var StrFirstName:String!
var StrLastName:String!
var StrMobile:String!
init(fname:String , lname:String , mobile:String)
{
StrMobile = mobile
StrFirstName = fname
StrLastName = lname
}
}
Im doing this wrong I but I'm not sure how to get it I could really use some help. I have 3 sliders (I may need more later) and basically they are 1-10 in value kinda for a rating system and i want them averaged to create an average score.. so this is what I have
#IBOutlet weak var speed: UISlider!
#IBAction func speedChange(sender: AnyObject) {
let speedValue = speed.value
}
#IBOutlet weak var body: UISlider!
#IBAction func bodyChange(sender: AnyObject) {
let bodyValue = body.value
}
#IBOutlet weak var details: UISlider!
#IBAction func detailsChange(sender: AnyObject) {
let detailsValue = details.value
}
#IBOutlet weak var score: UILabel!
func final() {
var thescore = (speed.value + body.value + details.value) / 3
score.text = "\(thescore)"
}
Only problem is it doesn't work. the + errors out, so I need to fix that, but even still i think my methodology is completely off.
It worked for me. Are you sure the outlets in the storyboard are linked to your Controller ?
Also, you may want to call your function final every time a slider changed its value, like this :
#IBOutlet weak var sliderA: UISlider!
#IBAction func sliderAchanged(sender: AnyObject) {
fonction()
}
#IBOutlet weak var sliderB: UISlider!
#IBAction func sliderBchanged(sender: AnyObject) {
fonction()
}
#IBOutlet weak var sliderC: UISlider!
#IBAction func sliderCchanged(sender: AnyObject) {
fonction()
}
#IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
fonction()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func fonction() {
var thescore = (sliderA.value + sliderB.value + sliderC.value ) / 3
label.text = "\(thescore)"
}
And I added a call to the function in viewDidLoad method to initilaize the label's text.
import UIKit
class ViewController: UIViewController {
// Khai bao bien
var time:Float = 0
var timer:NSTimer!
var sliTime:Float!
// End khai bao
#IBOutlet weak var sldTime: UISlider!
#IBOutlet weak var lblScore: UILabel!
#IBOutlet weak var lblNum1: UILabel!
#IBOutlet weak var lblOperator: UILabel!
#IBOutlet weak var lblNum2: UILabel!
#IBOutlet weak var lblResult: UILabel!
#IBAction func btnOK(sender: AnyObject) {
}
#IBAction func btnCan(sender: AnyObject) {
}
override func viewDidLoad() {
super.viewDidLoad()
sldTime.minimumValue = 0
sldTime.maximumValue = 10
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("Run") ,userInfo: nil, repeats: true)
}
func Run()
{
if time == 0{
time = 10
}else{
time = time - 1
sldTime.value = time
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
When I run app in simulator , the app show:
"Thread 1 breakpoint 1.1" in line sldTime.value = time
What does the debugger console say? Thread 1: signal SIGABRT error if that's what the console says that mean you made a bad connection from the Main Story board to the ViewController Go to the Outlet Connection > and delete a connection you made but it's no longer in use. And try to run it again. Just keep in mind that Thread 1: signal SIGABRT Error is due to a connection problem between the Storyboard and ViewController mostly.
time = sldTime.floatValue
This question already has answers here:
Unrecognized selector sent to instance NSTimer Swift
(3 answers)
Closed 8 years ago.
I'm making an app where you need to indicate the amount of time that a label appears for and that amount of time is counted down at the bottom of the page.
When I run my app on the Xcode simulator, the chronometre label displays "Optional (*indicated number)" when I want it to only display the indicated number. Once it's displayed for a second, I get taken to my App Delegate and it says Thread 1: signal SIGABRT.
The following error is also shown: 2015-02-22 21:05:50.860 MemoPres.New[71008:12980314] -[MemoPres_New.ViewController subtractTime:]: unrecognized selector sent to instance 0x7fbab24299c0
2015-02-22 21:05:50.862 MemoPres.New[71008:12980314] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[MemoPres_New.ViewController subtractTime:]: unrecognized selector sent to instance 0x7fbab24299c0'.
Help would be greatly appreciated.
The following is all of my code:
class ViewController: UIViewController {
#IBOutlet weak var chronometre: UILabel!
#IBOutlet weak var prochainpointLabel: UILabel!
#IBOutlet weak var pointactuelLabel: UILabel!
#IBOutlet weak var point1Textfield: UITextField!
#IBOutlet weak var point1tempsTextfield: UITextField!
#IBOutlet weak var point2Textfield: UITextField!
#IBOutlet weak var point2tempsTextfield: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func presenterButton(sender: AnyObject) {
var timer = NSTimer()
var seconds = point1tempsTextfield.text.toInt()
pointactuelLabel.text = point1Textfield.text
prochainpointLabel.text = point2Textfield.text
chronometre.text = "\(seconds)"
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: ("subtractTime:"), userInfo: nil, repeats: true)
func subtractTime(dt:NSTimer){
seconds!--
chronometre.text = "\(seconds)"
}
}
}
You need to declare your method subtractTime() outside your IBAction. The same applies to your timer and second vars.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var progressView: UIProgressView!
#IBOutlet weak var strTimer: UILabel!
#IBOutlet weak var btnStartCancel: UIButton!
#IBOutlet weak var btnPauseResume: UIButton!
var timer = Timer()
var startTime: TimeInterval = 0
var timeLeft: TimeInterval = 45
var isTimerON = false
var isPaused = false
func updateTimer() {
if isTimerON && !isPaused {
strTimer.text = (startTime - Date().timeIntervalSinceReferenceDate).time
progressView.progress = (1 - Float(startTime - Date().timeIntervalSinceReferenceDate) / 45)
}
}
override func viewDidLoad() {
super.viewDidLoad()
timer = .scheduledTimerWithTimeInterval(1/20, target: self, selector: "updateTimer", userInfo: nil, repeats: true)
RunLoop.main.addTimer(timer, forMode: .common)
}
#IBAction func pauseResumeAction(_ sender: Any) {
isPaused = !isPaused
if isPaused {
timeLeft = startTime - Date().timeIntervalSinceReferenceDate
}
startTime = Date().dateByAddingTimeInterval(timeLeft).timeIntervalSinceReferenceDate
btnPauseResume.setTitle( !isPaused ? "Pause" : "Resume", forState: .normal)
}
#IBAction func startCancelAction(_ sender: Any) {
isTimerON = !isTimerON
isPaused = false
timeLeft = 45
startTime = isTimerON ? Date().dateByAddingTimeInterval(timeLeft).timeIntervalSinceReferenceDate : timeLeft
btnStartCancel.setTitle(!isTimerON ? "Start" : "Cancel", forState: .normal)
progressView.progress = 0
btnPauseResume.setTitle("Pause", forState: .normal)
strTimer.text = "00:45"
btnPauseResume.enabled = isTimerON
}
}
extension TimeInterval {
var time: String {
String(format: "%02d:%02d", Int((self/60)%60), Int(self%60))
}
}