I have the string like "123456". And I have 6 labels. I need to split each number and I have to print in to each label.
Like my labels are:
Lab1 Lab2 Lab3 Lab4 Lab5 Lab6 ==== In screen design
My output have to:
1 2 3 4 5 6
How can I split that each number and how I will display in my each label..I can also use 6 let or var to save each value and I can display it. But I don't know the functionality to b done.
Given text
let text = "123456"
You need to transform it into an Array of String(s).
let list = text.characters.map { String($0) }
Now you can check the array has at least 6 elements and assign each element to the text property of each label
if list.count > 5 {
lab1.text = list[0]
lab2.text = list[1]
lab3.text = list[2]
lab4.text = list[3]
lab5.text = list[4]
lab6.text = list[5]
}
You can use simple ForIn Loop :
#IBOutlet weak var lbl1: UILabel!
#IBOutlet weak var lbl2: UILabel!
#IBOutlet weak var lbl3: UILabel!
#IBOutlet weak var lbl4: UILabel!
#IBOutlet weak var lbl5: UILabel!
#IBOutlet weak var lbl6: UILabel!
let word = "123456"
func splitWord(){
// Swift 3.1
for (i,char) in word.characters.enumerated(){
switch i {
case 0:
lbl1.text = "\(char)"
case 1:
lbl2.text = "\(char)"
case 2:
lbl3.text = "\(char)"
case 3:
lbl4.text = "\(char)"
case 4:
lbl5.text = "\(char)"
case 5:
lbl6.text = "\(char)"
default:
print("Out of bound")
}
}
}
Related
Im trying to be able to multiply the data in the label of price(1-3) by the counterValue to show the price for for each option that is selected
So far my code can multiply the counterValue by the factor of the selected optionBtn(1-3) when selected
What Im trying to do is multiply the counter value by the label data of the Price labels
All price labels are Floats I've tried using this code Int(Float(modifyItems.cart.price1)) to replace the factor variable in the 'if statements' but still no success
SideNote: The data that populates the labels in the ModifyVC is passed from another VC. A delegate passes the data into the ModifyVC and the data is retrieved from cloud Firestore (as seen in the viewDidLoad)
thank in advanced for any help that is given
class ModifyViewController: UIViewController {
private var counterValue = 1
var lastSelectedWeightButton = RoundButton()
var modifyItems: Cart!
#IBOutlet weak var price1: UILabel!
#IBOutlet weak var price2: UILabel!
#IBOutlet weak var price3: UILabel!
#IBOutlet weak var weight1: UILabel!
#IBOutlet weak var weight2: UILabel!
#IBOutlet weak var weight3: UILabel!
#IBOutlet weak var lblQty: UILabel!
#IBOutlet weak var modifyTotal: UILabel!
#IBOutlet weak var option1: RoundButton!
#IBOutlet weak var option2: RoundButton!
#IBOutlet weak var option3: RoundButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let formatter = NumberFormatter()
formatter.maximumFractionDigits = 2
formatter.numberStyle = .decimal
price1.text = "$\(formatter.string(for: modifyItems.cart.price1)!)"
price2.text = "$\(formatter.string(for: modifyItems.cart.price2)!)"
price3.text = "$\(formatter.string(for: modifyItems.cart.price3)!)"
weight1.text = modifyItems.cart.weight1
weight2.text = modifyItems.cart.weight2
weight3.text = modifyItems.cart.weight3
}
#IBAction func minusQty(_ sender: AnyObject) {
if(counterValue != 1){
counterValue -= 1
}
self.lblQty.text = "\(counterValue)"
var factor = 1
if option1.isSelected {
factor = 13
} else if option2.isSelected {
factor = 39
} else if option3.isSelected {
factor = 72
}
modifyTotal.text = "$\(factor * counterValue)"
print("Decrease Quantity")
}
}
class Cart {
var cart: Items!
init(cart: Items) {
self.cart = cart
}
}
You just store the label data to (Int or Float).
var total = 0
if modifyTotal.text != " " {
total = Int(modifyTotal.text.replacingOccurrences(of: "$", with: ""))!
}
let finalTotalValue = total + (factor * CounterValue)
modifyTotal.text = "$\(finalTotalValue)"
You can use NSExpression to evaluate your expression like
let nExpression = "1 * 5"
let expression = NSExpression(format: nExpression)
var result = expression.expressionValue(with: nil, context: nil) as? Int
I'm trying to get the int values from my labels and pass them to another label and add them together. In the code below, kicklabel, handballlabel, marklabel, etc., all need to add up and equal into fantasylabel. Based on how this code is set up, I'm not sure how to perform that.
I want to be able to add more lines of labels also, so that any amount of the array of labels add to a fantasy label.
Here's the code:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var kickLabel1: UILabel!
#IBOutlet weak var handballLabel1: UILabel!
#IBOutlet weak var markLabel1: UILabel!
#IBOutlet weak var tackleLabel1: UILabel!
#IBOutlet weak var goalLabel1: UILabel!
#IBOutlet weak var pointLabel1: UILabel!
#IBOutlet weak var freeForLabel1: UILabel!
#IBOutlet weak var freeAgainstLabel1: UILabel!
#IBOutlet weak var fantasyLabel: UILabel!
var counters: [UILabel: Int] = [:]
override func viewDidLoad() {
super.viewDidLoad()
for label: UILabel in [kickLabel1,handballLabel1,markLabel1,tackleLabel1,goalLabel1,pointLabel1, freeForLabel1, freeAgainstLabel1, fantasyLabel] {
counters[label] = 0
for direction: UISwipeGestureRecognizerDirection in [.up, .down, .left, .right] {
let swipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(didSwipe(_:)))
swipeGesture.direction = direction
label.addGestureRecognizer(swipeGesture)
label.isUserInteractionEnabled = true
label.isMultipleTouchEnabled = true
}
}
}
#objc func didSwipe(_ gestureRecognizer: UISwipeGestureRecognizer) {
guard let label = gestureRecognizer.view as? UILabel else { return }
debugPrint("\(gestureRecognizer.direction)")
switch gestureRecognizer.direction {
case .up:
counters[label] = counters[label]! + 10
print(counters)
case .down:
counters[label] = 0
print(counters)
case .left:
counters[label] = counters[label]! - 1
print(counters)
case .right:
counters[label] = counters[label]! + 1
print(counters)
default:
counters[label] = 0
}
label.text = "\(counters[label]!)"
}
}
At the end of your didSwipe you need to sum all of the Int values stored in your counters dictionary. Then update your fantasy label with that sum.
let sum = counters.reduce(0) { $0 + $1.value }
fantasyLabel.text = "\(sum)"
And you probably don't want a gesture on the fantasy label since that value is read-only based on the sum of the other data.
I would also get rid of the individual label outlets except for the fantasy label. Use an IBOutletCollect to store an array of UILabel.
I have a scene in my app that I want to do basic math between two slider bars and a segmented control that the user picks. I am trying to do the math between variables under the segmented controls, but Xcode is giving me a (!) stating
Use of unresolved identifier "xxxx"
with whatever variable I'm trying to add.
My code is:
import UIKit
class DopamineCalculator: UIViewController {
//slider outlets
#IBOutlet weak var slider: UISlider!
#IBOutlet weak var sliderone: UISlider!
//segmentoutlet
#IBOutlet weak var segmentoutlet: UISegmentedControl!
//LABELS
//weight label
#IBOutlet weak var weightlabel: UILabel!
//dosage label
#IBOutlet weak var dosagemg: UILabel!
//Drip Rate Answer Label
#IBOutlet weak var dripanswer: UILabel!
//ACTIONS!!
//weight slider action
#IBAction func weightslider(sender: UISlider) {
let weight = Int(sender.value)
//converts to kgs
let kgs = Int(sender.value) / Int(2.2)
weightlabel.text = "\(weight) lbs"
}
//Dosage Desired dosage slider
#IBAction func dosagedesired(sender: UISlider) {
let dosage = Int(sender.value)
dosagemg.text = "\(dosage) mg"
}
//CONCENTRATION OPTIONS
#IBAction func concentrationoption(sender: UISegmentedControl) {
switch segmentoutlet.selectedSegmentIndex
{
case 0:
dripanswer.text = (kgs) * (dosage) / 800
case 1:
dripanswer.text = "1600";
case 2:
dripanswer.text = "3200";
default:
break;
}
}
What I am trying to do is kgs x dosage / 800 respectively for each case. I can not find an adequate solution online to the unresolved identifier issue.
#IBOutlet ...
// Add variables to be reachable for all methods
var dosage : Int = 0
var kgs : Double = 0.0
var divisor : Double = 800.0
#IBAction func dosagedesired(sender: UISlider) {
// prepend self to variable as it is used
self.dosage = Int(sender.value)
dosagemg.text = "\(self.dosage) mg"
// adding the calculation here
let result = self.kgs * Double(self.dosage) / self.divisor
dripanswer.text = "\(result)"
}
#IBAction func weightslider(sender: UISlider) {
let weight = Int(sender.value)
// converts to kgs
// the same here
self.kgs = Int(sender.value) / Int(2.2)
// adding the calculation here
let result = self.kgs * Double(self.dosage) / self.divisor
dripanswer.text = "\(result)"
}
#IBAction func concentrationoption(sender: UISegmentedControl) {
switch segmentoutlet.selectedSegmentIndex
{
case 0:
self.divisor = 800.0
case 1:
self.divisor = 1600.0
case 2:
self.divisor = 3200.0
default:
self.divisor = 800.0
}
// finally the calculation
let result = self.kgs * Double(self.dosage) / self.divisor
dripanswer.text = "\(result)"
}
You should declare the variables kgs and dosage outside of any method i.e. at the class level, along with your outlets
//slider outlets
#IBOutlet weak var slider: UISlider!
#IBOutlet weak var sliderone: UISlider!
//segmentoutlet
#IBOutlet weak var segmentoutlet: UISegmentedControl!
//LABELS
//weight label
#IBOutlet weak var weightlabel: UILabel!
//dosage label
#IBOutlet weak var dosagemg: UILabel!
//Drip Rate Answer Label
#IBOutlet weak var dripanswer: UILabel!
// You should declare the variables here:
var kgs = 0
var dosage = 0
And when you use kgs and dosage inside your methods, remove the word let because you're not declaring a variable.
The reason you do this is that you can't access variables declared in a method in another method. In the concentrationoption method, you can't access dosage, which is defined in dosagedesired method.
Right now I have 3 Textfields where users can input numbers and I want to have all 3 textfields be added together and broadcasted into either another label or textfields later down the page. Is this something that can be done?
Right now I have the following for the 3 textfields
#IBOutlet var waistText1: UITextField!
#IBOutlet var waistText2: UITextField!
#IBOutlet var waistText3: UITextField!
and for the label where the data needs to go;
#IBOutlet var wavgText: UILabel!
My first idea was something like;
wavgText.text = waistText1 + waistText2 + waistText3;
Just parse the textfields text as integer, add the values and convert back to string.
#IBOutlet var valueLabel: UILabel!
func updateValueLabel() {
let number1 = Int(waistText1?.text ?? "") ?? 0
let number2 = Int(waistText2?.text ?? "") ?? 0
let number3 = Int(waistText3?.text ?? "") ?? 0
valueLabel.text = String(number1 + number2 + number3)
}
I have a label that displays a random emoji, and then I have 4 UIButtons. Each one will display a random emoji, and one of the 4 will display the same emoji as the one on the label. Its a matching game.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var faceLabel: UILabel!
#IBOutlet weak var scoreLabel: UILabel!
var randomEmojiNum: UInt32 = arc4random_uniform(6) + 1
override func viewDidLoad() {
super.viewDidLoad()
faceLabel.text = genRanNum()
}
func genRanNum() -> String{
switch randomEmojiNum{
case 1: return "😀"
case 2: return "😅"
case 3: return "😉"
case 4: return "😁"
case 5: return "😂"
case 6: return "😄"
default: break
}
return "Default"
}
func correctAnswerGen() {
var correct: UInt32 = arc4random_uniform(4)
switch correct{
case 0: topLeftAnswer.titleLabel?.text = genRanNum()
case 1: topRightAnswer.titleLabel?.text = genRanNum()
case 2: bottomRightAnswer.titleLabel?.text = genRanNum()
case 3: bottomLeftAnswer.titleLabel?.text = genRanNum()
default: break
}
}
#IBOutlet weak var topLeftAnswer: UIButton!
#IBOutlet weak var topRightAnswer: UIButton!
#IBOutlet weak var bottomLeftAnswer: UIButton!
#IBOutlet weak var bottomRightAnswer: UIButton!
}
But every time I run it, it doesn't go as expected. Right now I'm assigning randomly one of the 4 UIButton outlets to be set to the same emoji as the one on the label, however none of the outlets set!
Whenever I run it looks like it is being selected. None of the buttons ever get set! I have a hunch it has something to do with the outlets being set and me editing the value after they are set. However, if i knew, i wouldn't be asking for help! Haha cheers!
Instead of topLeftAnswer.titleLabel?.text just use:
topLeftAnswer.setTitle("emoji", forState: UIControlState.Normal)
This is how I accomplished this:
class ViewController: UIViewController {
#IBOutlet weak var faceLabel: UILabel!
#IBOutlet weak var scoreLabel: UILabel!
#IBOutlet weak var topLeftAnswer: UIButton!
#IBOutlet weak var topRightAnswer: UIButton!
#IBOutlet weak var bottomLeftAnswer: UIButton!
#IBOutlet weak var bottomRightAnswer: UIButton!
var randomEmojiNum: UInt32 = arc4random_uniform(6) + 1
override func viewDidLoad() {
super.viewDidLoad()
faceLabel.text = genRanNum()
correctAnswerGen()
}
func genRanNum() -> String{
switch randomEmojiNum{
case 1: return "😀"
case 2: return "😅"
case 3: return "😉"
case 4: return "😁"
case 5: return "😂"
case 6: return "😄"
default: break
}
return "Default"
}
func correctAnswerGen() {
var correct: UInt32 = arc4random_uniform(4)
switch correct{
case 0: topLeftAnswer.setTitle(genRanNum(), forState: UIControlState.Normal)
case 1: topRightAnswer.setTitle(genRanNum(), forState: UIControlState.Normal)
case 2: bottomLeftAnswer.setTitle(genRanNum(), forState: UIControlState.Normal)
case 3: bottomRightAnswer.setTitle(genRanNum(), forState: UIControlState.Normal)
default: break
}
}
}
Update : Edited According to OP requirement.