Nesting buttons in Swift - swift

How can a button press another button. I want to know how to press button2 and have button1 complete its task and relay that information to button2. I feel like this answer is super simple, and any help would be greatly appreciated.
#IBOutlet weak var textField1: UITextField!
#IBOutlet weak var textField2: UITextField!
#IBAction func button1(sender: AnyObject) {
var textAgeArray = ["1", "2", "3"]
let randomTextAge = Int(arc4random_uniform(UInt32(textAgeArray.count)))
let displayAge = textAgeArray[randomTextAge]
textField1.text = displayAge
}
#IBAction func button2(sender: AnyObject) {
textField2.text = displayAge
}

You are using these buttons to update particular text field when a button is pressed, so put that task inside a function and then call that function from any button. If you want to track that then add a variable to check what is current text. What you are trying to do can be done through this way because you don't want to press button you want to do particular task.

As Mukesh suggested you can refactor your code, with a separate method of the repeated code.
Just thought I'd post an alternative solution. You can call the button1 method from inside of button2:
#IBOutlet weak var textField1: UITextField!
#IBOutlet weak var textField2: UITextField!
var displayAge: String?
#IBAction func button1(sender: AnyObject) {
var textAgeArray = ["1", "2", "3"]
let randomTextAge = Int(arc4random_uniform(UInt32(textAgeArray.count)))
displayAge = textAgeArray[randomTextAge]
textField1.text = displayAge
}
#IBAction func button2(sender: AnyObject) {
button1(sender)
textField2.text = displayAge
}
Note that you must take the displayAge variable out so that the button2 method can access it. This will make textField1 and textField2's text the same. I'm not sure if that's the desired result as I can't tell from your post. If you want these to be different random fields then I would suggest you refactor it to have the repeated method separate.
This will also set both of the text fields at the same time. If you don't want to refactor your code to only set one field at a time then you could start tagging your button's to see where the call is coming from:
#IBOutlet var button1: UIButton!
#IBAction func button1(sender: AnyObject) {
var textAgeArray = ["1", "2", "3"]
let randomTextAge = Int(arc4random_uniform(UInt32(textAgeArray.count)))
displayAge = textAgeArray[randomTextAge]
// if sender is this button, then update text, otherwise don't do anything
if sender.tag == 1 {
textField1.text = displayAge
}
}
By default tags are 0, but you can change them by set them like so: (You can put this in viewDidLoad)
button1.tag = 1
May as well add the solution by refactoring for completeness:
#IBOutlet weak var textField1: UITextField!
#IBOutlet weak var textField2: UITextField!
#IBAction func button1(sender: AnyObject) {
let displayAge = randomTextAge()
textField1.text = displayAge
}
#IBAction func button2(sender: AnyObject) {
let displayAge = randomTextAge()
// Uncomment the line below if you want to update textField1 with the same value
// textField1.text = displayAge
textField2.text = displayAge
}
func randomTextAge() -> String {
var textAgeArray = ["1", "2", "3"]
let randomTextAge = Int(arc4random_uniform(UInt32(textAgeArray.count)))
let displayAge = textAgeArray[randomTextAge]
return displayAge
}

Related

How to get all iterations of a loop to a text field in swift xcode

First ever solo app attempt, creating a very simple basic app. Noob alert!
I am trying to get all iterations of this for in loop to the text field. Only the last value shows up whereas when printed they all show up. Any noob guidance is appreciated :)
#IBOutlet weak var shelfSize: UITextField!
#IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
shelfSize.delegate = self
super.viewDidLoad()
}
#IBAction func enterTapped(_ sender: UIButton) {
calculateCoursing()
}
func calculateSizing() {
let shelfHeight = Int(shelfSize.text!)
let veryTight = shelfSize! + 8
for index in 1...10 {
print("Course \(index) = \(index * veryTight)")
textView.text = "Course \(index) = \(index * veryTight)"
}
}

Button as a variable

I am trying to have a variable set to a buttons label.
I have something like this:
#IBOutlet weak var myButton: UIButton!
var myVariable = String()
#IBAction func ButtonPressed(_ sender: Any) {
myVariable = myButton.titleLabel
}
Can anyone tell my how I can make this work?
titleLabel is an instance of UILabel. Your myVariable is a String property. That does not match typewise. You can access titleLabel directly, as in:
myVariable = myButton.titleLabel?.text ?? ""
But UIButton class defines a title(for:) method to access title of the button for various states.
Thus, in your case I would recommend using following:
#IBOutlet weak var myButton: UIButton!
var myVariable = String()
#IBAction func ButtonPressed(_ sender: Any) {
myVariable = myButton.title(for: .normal) ?? ""
}
You're nearly there, you're just missing the text property. Also you might want to set your variable as an optional.
#IBOutlet weak var myButton: UIButton!
var myVariable: String?
#IBAction func ButtonPressed(_ sender: Any) {
myVariable = myButton.titleLabel?.text
}

unsure how to unwrap uilabel optional to calculate my to uilabels

I am new in the developer world and have been on and off since february with swift and Xcode. I am hoping someone could help me out. Im trying to make a simple tip calculator and can't seem to * two uilabels together. this is what i have so far... at the total.text = "(totalAmount) * (tipPercent)" ... thanks any help would be great. :)
#IBOutlet weak var totalAmount: UILabel!
#IBOutlet weak var textFIeld: UITextField!
#IBOutlet weak var tipPercent: UILabel!
#IBOutlet weak var slider: UISlider!
#IBOutlet weak var total: UILabel!
#IBOutlet weak var tip: UILabel!
#IBAction func sliderChanged(_ sender: UISlider) {
sldr()
total.text = "\(totalAmount) * \(tipPercent)"
}
#IBAction func buttonPressed(_ sender: Any) {
ttl()
}
func ttl() {
if let grandTotal = textFIeld.text {
totalAmount.text! = "\(grandTotal)"
}
}
func sldr() {
tipPercent.text! = "\(Int(slider.value))"
}
The below expression will just only return you a string without any multiplication that you are expecting.
total.text = "\(totalAmount) * \(tipPercent)"
You know how to unwrap the text as you have done in ttl. You should use the same approach here
if let totalTxt = totalAmount.text, let percentTxt = tipPercent.text {
//Then change to whatever scalar type you want
if let totalAmount = Float(totalTxt), let percent = Float(percentTxt) {
let totalBill = totalAmount * percent
total.text = "\(totalBill)"
}
}

Changing of text on button not permanent

I have four buttons in a single view, with texts "A", "B", "X", "Y" on them respectively. I expected to see the texts of btnA and btnB change respectively when I pressed on btnX and btnY respectively and then both of btnA and btnB turn green. Instead, when I pressed btnA, "A" changed to "1" and immediately changed back to "A" again. But btnB changed to "2" permanently as expected.
This problem may seem simple but I just can't get the expected result. I just started to learn Swift. Please help me. Thank you!
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var btnA: UIButton!
#IBOutlet weak var btnB: UIButton!
#IBOutlet weak var btnX: UIButton!
#IBOutlet weak var btnY: UIButton!
#IBAction func btnXPressed(_ sender: UIButton) {
btnA.titleLabel?.text = "1"
check()
}
#IBAction func btnYPressed(_ sender: UIButton) {
btnB.titleLabel?.text = "2"
check()
}
func check() {
if ((btnA.titleLabel?.text)! == "1") && ((btnB.titleLabel?.text)! == "2") {
btnA.backgroundColor = UIColor.green
btnB.backgroundColor = UIColor.green
}
}
}

Transfer TextField data between ViewControllers

I have ViewController, which has a textfield and a button. The user enters his name into the textfield and hits the DONE button. When he hits the button, he is segued to GifteeDetails, which is a different view controller. There is a label in that viewController that is supposed to display his name. But, his name doesn't show up. I don't receive an error.
Here's ViewController:
#IBOutlet weak var textGifteeName: UITextField!
#IBAction func toDetails(_ sender: Any) {
performSegue(withIdentifier: "toDetails", sender: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destDetails: GifteeDetails = segue.destination as! GifteeDetails
destDetails.nametext = textGifteeName.text!
destDetails.agetext = "\(Int(age)! - 2000 + 17)"
destDetails.locationstext = labelGifteeLocationsPreview.text!
destDetails.intereststext = labelGifteeInterestsPreview.text!
}
Here's GifteeDetails:
var nametext = String()
var agetext = String()
var locationstext = String()
var intereststext = String()
#IBOutlet weak var labelGifteeName: UILabel!
#IBOutlet weak var labelGifteeAge: UILabel!
#IBOutlet weak var labelGifteeLocations: UILabel!
#IBOutlet weak var labelGifteeInterests: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
nametext = labelGifteeName.text!
agetext = labelGifteeAge.text!
locationstext = labelGifteeLocations.text!
intereststext = labelGifteeInterests.text!
}
Sorry about all the !. Swift gives me an error unless I have them.
You are updating the strings nametext and others, which are not connected to your labels.
You need to replace this piece of code:
destDetails.nametext = textGifteeName.text!
destDetails.agetext = "\(Int(age)! - 2000 + 17)"
destDetails.locationstext = labelGifteeLocationsPreview.text!
destDetails.intereststext = labelGifteeInterestsPreview.text!
With:
destDetails.labelGifteeName.text = textGifteeName.text!
destDetails.labelGifteeAge.text = "\(Int(age)! - 2000 + 17)"
destDetails.labelGifteeLocations.text = labelGifteeLocationsPreview.text!
destDetails. labelGifteeInterests.text = labelGifteeInterestsPreview.text!
nametext is a String object, and it is different from labelGifteeName.text which is the String of the label you want to update.
If you use segue then pls remove it, and then create action method of that button in the FirstviewController and use pushViewController to move on the SecondviewController.
Swift 3
Example:
#IBAction func toDetails(_ sender: Any)
{
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "SecondView") as! SecondView
UserDefaults.standard.set(self. textGifteeName.text, forKey: "savedStringKey")
UserDefaults.standard.synchronize()
self.navigationController?.pushViewController(vc,
animated: true)
}
In SecondView:
override func viewDidLoad() {
super.viewDidLoad()
self.labelGifteeName.text = UserDefaults.standard.string(forKey: "savedStringKey")!
}
Please Update your func viewDidLoad() method in GifteeDetailsVC with labelGifteeName.text! = nametext , labelGifteeAge.text!= agetext instead of your code because you have already assigned the value in to strings i.e, nametext and agetext in ViewController, you need to display string value in label