printing percentage value into decimal swift - swift

The Result I wantedi have three buttons under same IBAction showing different percentages %0, %10, %20.
and I have another button called calculate in another IBAction. so what I want is. when I choose %10 and press calculate I want to print out the 0.1 in the console. this is very beginner question but I m really stuck here
below is my code
import UIKit
class CalculatorViewController: UIViewController {
#IBOutlet weak var billTextField: UITextField!
#IBOutlet weak var zeroPctButton: UIButton!
#IBOutlet weak var tenPctButton: UIButton!
#IBOutlet weak var twentyPctButton: UIButton!
#IBOutlet weak var splitNumberLabel: UILabel!
#IBAction func tipChanged(_ sender: UIButton) {
zeroPctButton.isSelected = false
tenPctButton.isSelected = false
twentyPctButton.isSelected = false
sender.isSelected = true
}
#IBAction func stepperValueChanged(_ sender: Any) {
}
#IBAction func calculatePressed(_ sender: UIButton) {
}
}

The easiest way is to add the output on the percentage button tapped, e.g. in the #IBAction of the "10%" button:
print("0.1")
If you really need to output on the Calculate button tap, you can first determine which percantage button is selected:
if zeroPctButton.isSelected {
print("0.0")
} else if tenPctButton.isSelected {
// ...
If you don't want to hardcode the output, you need some data to base on. Since you don't show us any model code, we can only rely on the text on the buttons. So, the solution might look something like this (inside the Calculate button's #IBAction):
[zeroPctButton,
tenPctButton,
twentyPctButton]
.filter { $0.isSelected }
.forEach {
print("\(Double(($0.titleLabel.text ?? "").filter { ("0"..."9").contains($0) }) / 100.0)")
}
(It takes the text of the selected percentage buttons, filters out only digits from it, converts the resulting digit string to Double, and divides the result by 100.0.)

Related

Troubles with starting value using UISlider

Started working on the application. There was the following problem, in Main.storyboard the current value is set for the slider (for the top one it is 1.5 out of 3, and for the bottom one it is 100 out of 200), therefore, in the screenshot, I should have points on the slider track in the middle. I started googling about it, I can't find anything. Xcode 12 problem maybe? If not, please help me write the correct search query. I will be very grateful.
Sorry for my bad English. :)
Here ViewController:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var heightLabel: UILabel!
#IBOutlet weak var weightLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func heightSliderChanged(_ sender: UISlider) {
print(sender.value)
heightLabel.text = String(format: "%.2f", sender.value) + "m"
}
#IBAction func weightSliderChanged(_ sender: UISlider) {
weightLabel.text = String(format: "%.0f", sender.value) + "Kg"
}
}
Property's for first slider:
Property's for second slider:
Yes, it's Xcode issues. You can find the issues list from this link. (https://fahimfarook.medium.com/xcode-12-and-ios-14-developer-bugs-and-issues-ada35920a104).
Create an outlet of both slider and set value through coding.
#IBOutlet weak var firstSlider: UISlider!
#IBOutlet weak var secondSlider: UISlider!
override func viewDidLoad() {
super.viewDidLoad()
firstSlider.minimumValue = 0
firstSlider.maximumValue = 3
firstSlider.value = 1.5
secondSlider.minimumValue = 0
secondSlider.maximumValue = 200
secondSlider.value = 100
}

How to allow dot or comma in UITextField in calculation?

I am newbie in coding. I just started to learn #swift and trying yo make a calculation app. My problem is my UITextField doesn't work with dot or comma.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var ilkLabel: UITextField!
#IBOutlet weak var ikinciLabel: UITextField!
#IBOutlet weak var sonucLabel: UILabel!
#IBOutlet weak var ilk2Label: UITextField!
#IBOutlet weak var ikinci2Label: UITextField!
#IBOutlet weak var sonuc2Label: UILabel!
#IBOutlet weak var ilk3Label: UITextField!
#IBOutlet weak var ikinci3Label: UITextField!
#IBOutlet weak var sonuc3Label: UILabel!
var sonuc:Double = 0
var sonuc2:Double = 0
var sonuc3:Double = 0
var deneme:Double = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
#IBAction func plusBtn(_ sender: Any) {
func forTrailingZero(temp: Double) -> String {
let tempVar = String(format: "%g", temp)
return tempVar
}
deneme = Double(Int(ikinciLabel.text!)! + 100 / 100 * Int(ilkLabel.text!)!)
sonucLabel.text = String(forTrailingZero(temp: Double(ikinciLabel.text!)! / 14.56 ) )
}
#IBAction func plus2Btn(_ sender: Any) {
}
#IBAction func plus3Btn(_ sender: Any) {
}
}
I expect to make calculation like 1.4 + 2.35 but when i try the app crashes. I can only calculate whole number like 2 + 2.
#matt is right. If the text in ikinciLabel is not an Int, the app crashes. You tell it to crash by using the force unwrap operator: !.
In general
You should only force-unwrap things when you are absolutely sure that the thing you want to unwrap is not nill. In all other cases you should if-let or guard-let the optional, use the nil-coalescing operator (??) (or other ways to unwrap optionals) and handle the nil-case.
In your case
if you want to allow the user to enter floating point numbers using either a comma or a dot, you could simply replace every comma with a dot like so:
let enteredTextWithoutComma = textField.text?.replacingOccurrences(of: ",", with: ".")
This new constant is an optional. To safely make a Double out of it, do:
guard let enteredTextWithoutCommaUnwraped = enteredTextWithoutComma,
let enteredNumber = Double(enteredTextWithoutCommaUnwraped) else {
// one of the two actions didn't work. Maybe the entered phrase was not a number
// do something
return
}
// here you can use the variable enteredNumber. It is now a Double (not an Optional)
...

How do I change the text of a label with a segmented controller that has three segments>

For class I have a segmented controller that has three segments.
First segment: make label say Hello
Second segment make label say goodbye
Third segment make label say you rock.
I also need to add a name entered by a text field and when a button is pushed it goes into the label either starting with Hello, Goodbye, or You Rock.The picture is showing what I have so far.
second picture shows what I need to do
You can get the title of the selected segment and insert it into the name label text.
class ViewController: UIViewController {
// MARK: Outlets
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var greetingControl: UISegmentedControl!
// MARK: Properties
var name: String? {
return nameTextField.text
}
var greeting: String? {
return greetingControl.titleForSegment(
at: greetingControl.selectedSegmentIndex
)
}
// MARK: Methods
private func updateOutlets() {
nameLabel.text = "\(greeting!), \(name!)!"
}
// MARK: Actions
#IBAction func changeNameOnTap(_ sender: UIButton) {
updateOutlets()
}
#IBAction func nameController(_ sender: UISegmentedControl) {
updateOutlets()
}
}

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
}
}
}

UITextfield value for each indexpath.row

My uitableview consists of 10 cells and each cell has 2 uitextfield's.
I need to take values from each uitextfield in each cell and add it to an array
// my custom cell
class MatchTableViewCell: UITableViewCell, UITextFieldDelegate {
#IBOutlet weak var Team2Score: UITextField!
#IBOutlet weak var Team1Score: UITextField!
#IBOutlet weak var Team2: UILabel!
#IBOutlet weak var Image2: UIImageView!
#IBOutlet weak var Image1: UIImageView!
#IBOutlet weak var Team1: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
Make sure in the cell initializer for tableviewcontroller that your using your custom cell name and that you've set your identifier correctly. Then just initalize a cell and say something to the effect of
cell.Team2Score.text = "100"
you will need a global array to hold the strings. So..
var wordArray: [String] = []
you will need to add a button within the cell so when you hit the button it will add (append in the input of string (letters) to the array.
You need to add a tag to the button to know which cell it was clicked in.
button.tag = indexPath.row
#IBaction button(sender: UIButton){
var team2Words = Team2Score.text
wordArray.append(team2Words)
// do the samething for Team1Score
// you can use and if statement to check if one or the other one is empty
}
This will give you a lead