Change the text of a label with a button in iOS - ios

Firstly, let me say I'm new to Swift and Xcode. I have a label that displays some text and I want that text to change when a button is pressed.
Here is the code in the UIViewController:
var txt = "Hey"
#IBOutlet weak var Text: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
showText()
}
func showText(){
Text.text = txt
}
#IBAction func Button(_ sender: Any) {
txt = "Hello"
}
The buttons and labels are correctly linked to their main.storyboard counterparts. When I run this and press the button the text doesn't change.

viewDidLoad() is only called one time when the ViewController is created. showText() needs to be called after txt is set if you want to display it. One way to automate this is to add a property observer to txt to call showText() when txt is updated:
var txt = "Hey" {
didSet {
showText()
}
}

I will add that it is more flexible and perhaps elegant to have your showText() method take the actual text to show as an argument, instead of depending on some internal state (the value of the property txt: String, that isn't immediately evident at the call site) to accomplish its task:
#IBOutlet weak var textLabel: UILabel!
func showText(_ text: String){
self.textLabelabel?.text = text
// (optional chaining to avoid crash if accidentally
// called before viewDidLoad())
}
#IBAction func buttonAction(_ sender: Any) {
self.showText("Hello") // From here it is clear what text will be shown
}

change your code as per below
var txt = "Hey"
#IBOutlet weak var Text: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
showText()
}
func showText(){
Text.text = txt
}
#IBAction func Button(_ sender: UIButton) {
txt = "Hello"
showText()
}

Change Text of label with button just need to pass the text in label;
//Outlets
#IBOutlet weak var firstLabel: UILabel!
#IBOutlet weak var secondLabel: UILabel!
//Button Action
#IBAction func textChabge(_ sender: Any) {
firstLabel.text = "newText"
secondLabel.text = "newText"
}

just change your IBAction like this.
#IBAction func Button(_ sender: Any) {
txt = "Hello"
showText()
}

Related

Unable to play a sequence of images while clicking on a button

I am trying to play separated images of an animated image by clicking on the next button. Image names were stored as strings in an array. When I click on next button, the image transition is happening for the first time. Next time, it is not happening. When I tried to print the value of i, to check what is happening when the next button is clicked, the value is not getting incremented. Below is my code:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var image2: UIImageView!
// #IBOutlet weak var imageView1: UIImageView!
// img1.image=UIImage(named:"frame2.gif")
#IBAction func next(_ sender: Any) {
var imgarray=["frame2.gif","frame3.gif","frame4.gif","frame5.gif","frame6.gif"]
var i=0
if i<7{
image2.image=UIImage(named:imgarray[i])
i+=1
}
else if i>=7{
i=0
}
print(i)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
}
put var i=0 outside the button action. Otherwise when you click on button your i will always reinitialize with 0
import UIKit
class ViewController: UIViewController {
var i=0
#IBOutlet weak var image2: UIImageView!
// #IBOutlet weak var imageView1: UIImageView!
// img1.image=UIImage(named:"frame2.gif")
#IBAction func next(_ sender: Any) {
var imgarray=["frame2.gif","frame3.gif","frame4.gif","frame5.gif","frame6.gif"]
if i<7{
image2.image=UIImage(named:imgarray[i])
i+=1
}
else if i>=7{
i=0
}
print(i)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
}

Thread 1 : 1.1 breakpoint on Xcode

i try to create my first application on Xcode ,first I tried only to overwrite the text of a label at same moment when it is write in a TextField.
Now I try just for fun , to set hidden a second label (Label2) from Utility area and with the button ok to keep these unhide but the I'll give error (Thread 1 :breakpoint 1.1).
After I try solve the problem, I think to save the text in a var String and when I press the "ok" button , it set the Label2.text=String.
Anyway ,When I build and run this code it give the same ERROR .
Anyone can help me ?
thanks
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var labelTitle: UILabel!;
#IBOutlet weak var labelRes: UILabel!;
#IBOutlet weak var textReceveirer: UITextField!;
var myString : String = " "
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func button(_ sender: UIButton) {
myString=textReceveirer.text!
labelRes.text = "hello \(myString)"
}
}
Try with the following code:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var labelOne: UILabel!;
#IBOutlet weak var textReciver: UITextField!;
override func viewDidLoad() {
super.viewDidLoad()
labelOne.text = " "
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func button(_ sender: UIButton) {
labelOne.text = textReciver.text
}
}
I think the error is at line
var String=""
String is data type ,
if you want to create variable type of string you may use follow this
var myVariable : String = ""
write in your code var String=""that replace with
var Variable : String = ""
or check that connection inspector..

Swift - Printing out the current value of a number

I'm currently developing a counter app which every time you press a button it will count up. I have already done this and works 100%, what I'm trying to do is make a another button and when you press it, it shows the current number on the console but it only prints out 0 because that's the default variable I assigned the value to.
My whole class:
var counterNumber = 0
#IBOutlet weak var counterLabel: UILabel!
func initCount(){
counterNumber = 0
}
func numberUp(){
self.counterNumber++;
counterLabel.text = "\(self.counterNumber)"
}
#IBAction func CountUp(sender: UIButton) {
numberUp()
}
#IBAction func RestartButton(sender: UIButton) {
initCount()
}
#IBAction func printButton(sender: UIButton) {
self.numberUp();
print(self.counterNumber)
}
override func viewDidLoad() {
super.viewDidLoad()
initCount()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Just call method numberUp in printButton: action.
var counterNumber = 0//this is a variable of class
#IBOutlet weak var counterLabel: UILabel!
#IBAction func printButton(sender: UIButton) {
self.numberUp();
print(self.counterNumber)
}
func numberUp(){
self.counterNumber++;
counterLabel.text = "\(self.counterNumber)"
}
Use 'self' keyword to call instance variables.
class ViewController: UIViewController {
// Properties
var counterNumber:Int = 0 // Make this variable Global to Class
// IBOutlets Properties
#IBOutlet weak var counterLabel: UILabel!
#IBAction func printButton(sender: UIButton) {
self.numberUp()
self.counterLabel.text = "\(self.counterNumber)"
print("\n You Pressed ==> \(sender.title) button \(self.counterNumber) times")
}
func numberUp() {
self.counterNumber += 1
self.counterLabel.text = "\(counterNumber)"
}
}

How to change label to original text after it's been changed with a function in Swift?

I have a button that changes a text view when it's pressed, I want it to do the changed text to be switched into the original text when the button is pressed again.
My Code:
//An IBOutlet for the textview
#IBOutlet weak var changingText: UITextView!
//The button that changed the text
#IBAction func viewChangedText(sender: AnyObject) {
changingText.text = "Changed Text"
}
Now I want the text changed back when the button is pressed again.
Note: The original text is in in the storyboard, and if possible. could you help me change the button's text to "View" when the original text is there and change the button's text to "Hide" when the changed text is there.
var didChange = false
#IBOutlet weak var changingText: UITextView!
//The button that changed the text
#IBAction func viewChangedText(sender: AnyObject) {
didChange = !didChange
if didChange {
changingText.text = "Changed Text"
}else{
changingText.text = "Original text"
}
}
#nathanwhy has a nice idea with the switch-bool. Building upon that idea you could have something like this:
#IBOutlet weak var changingTextView: UITextView!
var showOriginalText : Bool {
didSet {
changingTextView.text = showOriginalText ? "original text" : "other text"
}
}
override func viewDidLoad() {
super.viewDidLoad()
// or wherever else it makes sense
showOriginalText = true
}
#IBAction func changeButtonTapped(sender: UIButton) {
showOriginalText = !showOriginalText
}

Swift: Value Changing Control Events Not Calling?

So I have added targets to my IBActions I have created that occur when the value of a text field changes. When these actions occur, the system should check if the two text fields are both integers. I have set two variables set to false, and they are set to true when both of them are an int. In the IBActions, I have if statements that tell a button to be enabled if both of the variables contain integers. When I run the simulator, this button doesn't enable when both of the text fields contain an integer.
I am new to swift, so if possible, please write all of the code out and where it should be in my code. Here is what I have so far:
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var calculatorButton: UIButton!
#IBOutlet weak var inspirationLabel: UILabel!
#IBOutlet weak var beginningLabel: UILabel!
#IBOutlet weak var calculatorContainer: UIView!
#IBOutlet weak var answer1Label: UILabel!
#IBOutlet weak var doneButton: UIButton!
#IBOutlet weak var yourWeightTextField: UITextField!
#IBOutlet weak var calorieNumberTextField: UITextField!
#IBOutlet weak var menuExampleButton: UIButton!
#IBOutlet weak var aboutButton: UIButton!
#IBOutlet weak var calculateButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib
yourWeightTextField.delegate = self
calorieNumberTextField.delegate = self
calculateButton.enabled = false
// Calling the textfield valueChanged Methods
yourWeightTextField.addTarget(self, action:"yourWeightValueChanged:", forControlEvents:.ValueChanged);
calorieNumberTextField.addTarget(self, action:"calorieNumberValueChanged:", forControlEvents:.ValueChanged);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func calculatorButtonTapped(sender: AnyObject) {
calculatorContainer.hidden = false
inspirationLabel.hidden = true
beginningLabel.hidden = true
menuExampleButton.hidden = true
aboutButton.hidden = true
}
var yourWeightFilled = false
var calorieNumberFilled = false
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// Find out what the text field will be after adding the current edit
let text = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string)
// If the textfields have the properties of the function
if textField == yourWeightTextField {
yourWeightFilled = text.toInt() != nil
} else if textField == calorieNumberTextField {
calorieNumberFilled = text.toInt() != nil
}
return true
}
func textFieldShouldReturn(textField: UITextField) -> Bool
{
textField.resignFirstResponder();
return true;
}
// The methods to close the keyboard when editing is finished
#IBAction func yourWeightEditingDidEnd(sender: AnyObject) {
yourWeightTextField.resignFirstResponder()
}
#IBAction func calorieNumberEditingDidEnd(sender: AnyObject) {
calorieNumberTextField.resignFirstResponder()
}
#IBAction func yourWeightValueChanged(sender: AnyObject) {
// If both variables are true and the text fields contain integers, enable button
if self.yourWeightFilled && self.calorieNumberFilled {
self.calculateButton.enabled = true
}
}
#IBAction func calorieNumberValueChanged(sender: AnyObject) {
// If both variables are true and the text fields contain integers, enable button
if self.yourWeightFilled && self.calorieNumberFilled {
self.calculateButton.enabled = true
}
}
}
You should look for EditingChaged event, not ValueChanged
EDIT:
What I mean is to change from:
yourWeightTextField.addTarget(self, action:"yourWeightValueChanged:", forControlEvents:.ValueChanged);
calorieNumberTextField.addTarget(self, action:"calorieNumberValueChanged:", forControlEvents:.ValueChanged);
to :
yourWeightTextField.addTarget(self, action:"yourWeightValueChanged:", forControlEvents:.EditingChanged);
calorieNumberTextField.addTarget(self, action:"calorieNumberValueChanged:", forControlEvents:.EditingChanged);
You simply are looking for wrong event.
If you are looking for a text changed event , then Right Click on the text field select Editing Did End from the Sent Events . You can see a circle on the right end click the circle Hold Down Ctrl and Drag it to your ViewController file. Name the Action you want and . I have provided some screen shots for this.
Here i name the Action TextChanged
I am Using Xcode 7 Swift 2 here
Right Click on the Text Box and You can see Something Like this
Finally You can see the TextChanged event Created. when you type something on a text box and click return this event fires.

Resources