I want to have a function that gives the time. I already have a time label in my app that displays the current time, and updates every second. But I want to have a label that only holds the time a button is pressed. There are multiple buttons that store the current time in different labels.
func fetchTime() -> String {
return NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: NSDateFormatterStyle.NoStyle, timeStyle: NSDateFormatterStyle.MediumStyle)
}
#IBAction func clockIn(sender: AnyObject) {
testLabel = fetchTime()
The error I get is "Use of unresolved identifier 'fetch time'
I had this working awhile ago, but I accidentally deleted the app...
I also tried
func fetchTime(label: String) -> String{
label.text = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: NSDateFormatterStyle.NoStyle, timeStyle: NSDateFormatterStyle.MediumStyle)
}
But that failed badly, and I understand why, just not how to do it correctly.
Here is your both tried working version...
version1
func fetchTime(label: UILabel){
label.text = "its with parameter"
}
#IBAction func btnClicked(sender: UIButton) {
fetchTime(label)
}
And the another one...
func fetchTime() -> String {
return "without parameter"
}
#IBAction func btnClicked(sender: UIButton) {
lbl.text = fetchTime()
}
What you want to fetch is a string and that should be assigned as a label's text value.
Update
testLabel = fetchTime()
to
testlabel.text = fetchTime()
This will update the label's value each time when button is pressed.
The picture you posted was helpful. You've declared the fetchTime function inside the scope of the updateTime function. You'll notice the curly braces for updateTime wrap around fetchTime.
This being the case you can not call fetchTime outside of updateTime. Move fetchTime out of updateTime and you'll be ok. That is why you are seeing the undefined function error message.
Related
I have a function that runs when a button is pressed.
Inside that function is another function.
I would like to pass the pressed button into the inner function so that I can change the text of the button depending on stuff in that inner function.
#IBAction func newItem(sender: AnyObject) {
let urlFetch:String = urlField.text!
self.service.createNewItem(urlFetch, I_WANT_BUTTON_HERE)
}
How do I pass the button into the function?
If it helps this is the function that I am passing it to:
func createNewItem(item_url: String, plus_button: UIButton) {
let dataDictionary = ["url" : item_url]
self.post("item/create", data: dataDictionary).responseJSON { (response) -> Void in
plus_button.titleLabel!.text = "success"
}
}
Later I will add an if statement that changes the text depending on what the response is.
The object passed into newItem method is actually the button you tapped so you can securely convert the type of parameter sender into UIButton like below:
#IBAction func newItem(sender: UIButton) {
...
self.service.createNewItem(urlFetch, sender)
}
There is also one thing though. Setting the text of titleLabel is not the right way of updating the title of button. You should be using setTitle:forState instead:
func createNewItem(item_url: String, plus_button: UIButton) {
...
plus_button.setTitle("success", forState: .Normal)
}
Instead of sending AnyObject as parameter in the newItem function, pass a UIButton.
#IBAction func newItem(sender: UIButton) {
let urlFetch:String = urlField.text!
self.service.createNewItem(urlFetch, sender)
}
I'm finishing up a simple iOS8 app written in SWIFT which involves numbers being entered in at times. Sometimes the numbers need to be decimals and I noticed that unless I enter a 0 first before the decimal point, the decimal button won't work and nothing will be inputted into the text box.
I was thinking about just making the textbox start with 0, that way the user can just start typing in a decimal without have to enter in 0 by themselves first. I'm hoping there is a simple function that I can just use to solve this problem.
Thanks
Following works:
extension String {
func toDouble() -> Double? {
let fmt = NSNumberFormatter()
return fmt.numberFromString(self)?.doubleValue
}
}
and then in your view controller:
#IBOutlet weak var textField: UITextField!
#IBAction func convert(sender: AnyObject) {
if let d = textField.text.toDouble() {
println("Got a double \(d)")
} else {
println("Not a double \(textField.text)")
}
}
If it doesn't work for you, post more code, the problem is elsewhere.
In my program 2 functions (IBAction player.Move(UIButton) and autoMove()) are supposed to be called by turns till all of the fields (UIButtons) has been clicked. For this I've created a function play(). However, I don't know how can I put the IBAction playerMove inside of play() function, because I need no parameter here.
I've found some answers and tried self.playerMove(nil) and self.playerMove(self) but it doesn't work.
import UIKit
class ViewController: UIViewController {
#IBOutlet var cardsArray: Array<UIButton> = []
var randomCard = 0
override func viewDidLoad() {
super.viewDidLoad()
self.play()
// Do any additional setup after loading the view, typically from a nib.
}
func play () {
self.autoMove()
self.playerMove(self) // <----- here is my problem
}
#IBAction func playerMove(sender: UIButton) {
switch (sender) {
case self.cardsArray[0]:
self.cardPressedAll(0)
case self.cardsArray[1]:
self.cardPressedAll(1)
case self.cardsArray[2]:
self.cardPressedAll(2)
case self.cardsArray[3]:
self.cardPressedAll(3)
default: break
}
}
func cardPressedAll (cardNumber: Int) {
self.cardsArray[cardNumber].enabled = false
self.cardsArray[cardNumber].setBackgroundImage(UIImage(named: "cross"), forState: UIControlState.Normal)
self.cardsArray.removeAtIndex(cardNumber)
}
func autoMove (){
self.randomCard = Int(arc4random_uniform(UInt32(self.cardsArray.count)))
self.cardsArray[self.randomCard].enabled = false
self.cardsArray[self.randomCard].setBackgroundImage(UIImage(named: "nought"), forState: UIControlState.Normal)
self.cardsArray.removeAtIndex(self.randomCard)
}
}
Either you have to call playerMove: without a button, in which case you have to declare the sender parameter as an optional. Like:
#IBAction func playerMove(sender: UIButton?) {
UIButton means that you have to pass in a button. nil is not a button, but with UIButton?, that is to say Optional<UIButton>, nil is a valid value meaning the absence of a button.
Or you have to work out which button you want to pass to playerMove: to make it do what you want. Sit down and work out what you want to have happen, and what the code needs to do in order to make that happen.
Try
self.playerMove(UIButton())
Your func playerMove has parameters expecting sender to be of type UIButton, self or nil would be an unexpected object.
Edit:
You could us optional parameters by placing ?. This would allow you to call self.playerMove(nil) if needed.
#IBAction func playerMove(sender: UIButton?) {
if sender != nil {
//handle when button is passed
} else {
//handle when nil is passed
}
}
doSomeTask(UIButton()) in swift 5.0 and onward worked for me
I am new in Swift and I am making a simple calculator where I wan't to detect a button which was pressed and my code is below.
#IBAction func ButtonTapped(TheButton : UIButton){
println(TheButton.titleLabel.text)
}
But It Shows me error like "UILabel? Does not have a member a named text"
and it tell me to modify code like this
println(TheButton.titleLabel?.text)
This Prints Optional("1") (1 is my button name)
So anybody can help me why this is happend to me and how can I print my button name without Optional?
If you are sure that titleLabel is not nil:
println(TheButton.titleLabel!.text)
else
if let text = TheButton.titleLabel?.text {
println(text)
}
More simply, you could just do:
let titleValueString = TheButton.currentTitle!
If the button's title is not nil, the exclamation point (!) will implicitly unwrap the optional (currentTitle without the exclamation point) and you will have a string value for the title of the button in your constant, titleValueString
The top answer no longer works. Here is the corrected version for Swift 2.2:
If you are sure that titleLabel is not nil:
print(TheButton.titleLabel!.text!)
If you are not:
if let text = TheButton.titleLabel?.text {
print(text)
}
for Swift 5
There are many ways to do this but the easiest is just what I mentioned below:
#IBAction func keyPressed(_ sender:UIButton){
print(sender.currentTitle!)
}
Swift 5: I found this much cleaner
#IBAction func ButtonTapped(_ sender : UIButton){
guard let btnTxt = sender.titleLabel!.text else{
return
}
print(btnTxt)
// now you can make use of this variable
if btnTxt == "something" {
.......
}
}
I'm trying to make a simple app that counts the characters of a textfield, but when the user inputs the text, the function that converts the user-inputed string into a var and the function that counts the characters are executed at once. Here's the code:
import UIKit
class ViewController: UIViewController {
#IBOutlet var myTextField : UITextField
#IBOutlet var userTextField : UITextField
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
myTextField.text = fullConstant
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func modifyMyVariable(sender : AnyObject) {
myVariable = userTextField.text
}
#IBAction func clickMe(sender : AnyObject) {
countCharacters(&fullConstant)
println(fullConstant)
myTextField.text = fullConstant
}
}
And here's the "OtherFile.swift" where the functions are located:
import Foundation
var fullConstant = "Type something!"
var myVariable = ""
func modifyMyVariable() {
println()
}
func countCharacters(inout fullConstant: String) {
let FirstPart = "There are "
let LastPart = " characters"
var numberOfCharacters = countElements(myVariable)
switch numberOfCharacters {
case 0 :
fullConstant = "There isn't any character yet"
case 1 :
fullConstant = "There is just one character"
default :
fullConstant = FirstPart + String(numberOfCharacters) + LastPart
}
}
Both functions execute as soon the userTextField is edited, but if the user inputs one character, the countCharacters function takes the var myVariable before it's modified by the function modifyMyvariable, so it doesn't count the last character added.
To solve this, I've thought that I could call the function countCharacters from the function modifyMyVariable, so the variable myVariable has already changed when it counts the characters.
Change the following and see if it's then easier to fix your problem.
You should always only link each event to one IBAction. Your IBActions shouldn't be named after what you're trying to do in them; they should be named after the event that triggers them. For example, "modifyMyVariable" should be called "textEdited" or similar.
In that "textEdited" method, do all the work you need to do. If you need to call another function, call it from there instead of linking to two IBActions.
Put code in your "OtherFile" inside a
class OtherFile {
}
block, and hold an instance to that class as a variable in your view controller. You want to avoid declaring global functions outside of classes.
Not related, but name your constants using camelCase with first letter lower case, just like your variables. So FirstPart should be firstPart.
Avoid using 'inout' as much as possible. Each language has it's conventions; in ObjC and Swift, pass in values needed to do work, and return values that result from that work. So:
func countCharacters(text: String) -> (String)
Putting it all together, your 'modifyMyVariable' function (which should really be called 'textEdited') will look something like this:
myVariable = userTextField.text
let characterCount = self.myOtherFileInstance.countCharacters(myVariable)
myTextField.text = characterCount
and the other function (clickMe) should be deleted.