Swift - How to multiply value from UITextField - uitextfield

#IBOutlet weak var labelLabel: UILabel
#IBOutlet weak var textFieldField: UITextField
#IBAction func buttonButton(sender: AnyObject) {
var conversionRate = 7
self.labelLabel.text = self.textFieldField.text // Here I'm trying to multiply textFieldField by 7 (conversionRate)
textFieldField.resignFirstResponder()
}
Hello, I want to multiply a value from UITextField by 7. Can someone help me?
I've tried everything. .toInt(), intValue() and nothing

It should work with .toInt():
if let number = self.textFieldField.text?.toInt() {
self.labelLabel.text = "\(number * conversionRate)"
}

You can try this
var conversionRate = 7;
var value = self.nameLbl.text.toInt();
value = value!*conversionRate;
self.nameLbl.text = NSString(format:"%d",value!)as String;
OR
var conversionRate = 7;
var value : Int = self.nameLbl.text.toInt()!;
value = value*conversionRate;
self.nameLbl.text = String(value);
OR
var conversionRate = 7;
if let number = nameLbl.text?.toInt() {
self.nameLbl.text = "\(number * conversionRate)"
}

let a = textFieldField.text
let conversionRate = 7
let b = Int(a!)! * conversionRate //use Double(a!)! instead of Int(a!)! if your are using a floating point value for "conversionRate" variable.
labelLabel.text = ("\(b)")
Happy coding!

Related

How to use an array to fill the title text

I've created a customized keyboard using UIView. I'm trying to auto-fill the letters using a for loop but with no success.
func initializeSubviews() {
let xibFileName = "keyboardView" // xib extension not included b
let view = Bundle.main.loadNibNamed(xibFileName, owner: self, options: nil)![0] as! UIView
self.addSubview(view)
view.frame = self.bounds
setKeyboardText()
}
#IBOutlet var keyboardLetters: [myKeyboardBtn]!
func setKeyboardText() {
let str = "abcdefghijklmnopqrstuvwxyz"
let characterArray = Array(str)
for (Index, key) in keyboardLetters.enumerated() {
key.titleLabel?.text = String(characterArray[Index])
}
// [a,b,c,d,...]
}
what am I doing wrong?
According to Apple
"To set the actual text of the label, use setTitle(_:for:)
(button.titleLabel.text does not let you set the text)."

Swift Multiples App running error

I have running an issue with the Multiples App. I was just trying out and see if I can get the function right. However, this app can only run once, the addition itself is correct but when the game starts over, it will throw an error. Please help ~~
class ViewController: UIViewController {
#IBOutlet weak var AddBtn: UIButton!
#IBOutlet weak var TextInput: UITextField!
#IBOutlet weak var ResultLabel: UILabel!
var CurrentNum = 0
var SecondNum = 0
let MaxNum = 30
func currentNumUpdate(sum: Int, Mul: Int, nSum: Int){
ResultLabel.text = "\(sum) + \(Mul) = \(nSum)"
}
#IBAction func AddtionBtn(sender: UIButton) {
let TotalSum = CurrentNum + SecondNum
currentNumUpdate(CurrentNum, Mul: SecondNum, nSum: TotalSum)
CurrentNum += SecondNum
if (TextInput != nil && TextInput != ""){
SecondNum = Int(TextInput.text!)!
}
if GameOver(){
GameStartOver()
}
}
func GameOver() -> Bool{
if (CurrentNum > MaxNum){
return true
}else {
return false
}
}
func GameStartOver(){
ResultLabel.hidden = false
TextInput.text = ""
AddBtn.hidden = false
ResultLabel.text = "Again"
}
}

Sigabrt swift Xcode (making a timer)

I'm trying to make a stopwatch, and I can't seem to understand why I am getting a sigabrt with my application. Sorry I didn't know what to include, so I included everything.
var timer = NSTimer()
var minutes: Int = 0
var seconds: Int = 0
var fractions: Int = 0
var startStopWatch: Bool = true
var StopwatchString: String = ""
#IBOutlet weak var display: UILabel!
#IBAction func start(sender: UIButton) {
if startStopWatch == true {
NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: Selector("updateStopwatch"), userInfo: nil, repeats: true)
startStopWatch = false
} else {
timer.invalidate()
startStopWatch = true
}
}
#IBAction func reset(sender: UIButton) {
}
override func viewDidLoad() {
super.viewDidLoad()
display.text = "00:00.00"
}
func updateStopWatch() {
fractions += 1
if fractions == 100 {
seconds += 1
fractions = 0
}
if seconds == 60 {
minutes += 1
seconds = 0
}
let fractionsString = fractions > 9 ? "\(fractions)" : "0\(fractions)"
let secondsString = seconds > 9 ? "\(seconds)" : "0\(seconds)"
let minutesString = minutes > 9 ? "\(minutes)" : "0\(minutes)"
StopwatchString = "\(minutesString):\(secondsString).\(fractionsString)"
display.text = StopwatchString
}
I cut and pasted your code into a project and when I tapped the start button the first line of the error message said:
-[My.ViewController updateStopwatch]: unrecognized selector sent to instance 0x7fe0034b3520
That tells you all you need to know. You send the updateStopwatch message to your view controller but it doesn't implement that method. I noticed though that your ViewController does implement an updateStopWatch method. Looks like a basic capitalization error to me.
Always, always, always, read at least the first line of the error message.
Here are some fixes:
+I changed the timer variable initially to nil - it will be saved in the start function.
+Your if statement in the start function looked like this:
if startStopWatch == true
But it should be like this:
if (startStopWatch)
Hope this helpes :)
var timer = nil
var minutes = 0
var seconds = 0
var fractions = 0
var startStopWatch = true
var StopwatchString = ""
#IBOutlet weak var display: UILabel!
#IBAction func start(sender: UIButton) {
if (startStopWatch == true) {
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: Selector("updateStopwatch"), userInfo: nil, repeats: true)
startStopWatch = false
//I added one thing. If the start button is pushed the text will change to stop. You can change this if you like.
sender.setTitle("Stop", forState: .Normal)
//
} else {
timer.invalidate()
startStopWatch = true
}
}
#IBAction func reset(sender: UIButton) {
display.text! = "00:00.00"
}
override func viewDidLoad() {
super.viewDidLoad()
display.text! = "00:00.00"
}
func updateStopWatch() {
fractions++
if (fractions == 100) {
seconds++
fractions = 0
}
if (seconds == 60) {
minutes++
seconds = 0
}
var fractionsString = fractions > 9 ? "\(fractions)" : "0\(fractions)"
var secondsString = seconds > 9 ? "\(seconds)" : "0\(seconds)"
var minutesString = minutes > 9 ? "\(minutes)" : "0\(minutes)"
StopwatchString = "\(minutesString):\(secondsString).\(fractionsString)"
display.text! = StopwatchString
}

String does not have a member named 'text' error in Swift

I'm having issue with getting my let c:Int? = conversion.text.toInt() to convert correctly. I'm keep getting '[String]' does not have a member named 'text' error. Anybody know how to convert variable into integer?
I can't seem to get a to multiply to c.
#IBOutlet var pickerView1: UIPickerView!
#IBOutlet var textField1: UITextField!
#IBOutlet weak var enterUnits: UITextField!
#IBOutlet var answerConversion: UITextField!
var brand = ["m to feet","cm to inches", "mm to inches"]
var conversion = ["3","4", "5”]
pickerView function
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView.tag == 0 {
let a:Int? = enterUnits.text.toInt()
let b:Int? = answerConversion.text.toInt()
let c:Int? = conversion.text.toInt()
let answer = (a!) * (c!)
textField1.text = brand[row]
answerConversion.text = conversion[row]
answerConversion.text = "\(answer)”
}
I saw here that you don't necessarily need the .text. Try to just use
let c:Int? = conversion.toInt()
Oh and since conversion is an array, you would have to access the string you want to use. Try doing that with something like conversion[index] (insert the index which you' like to use)
Another way I found is to do it the following:
let c:Int = Int(conversion[index].bridgeToObjectiveC().intValue)
Hope that helps :)

errors while trying to compare a string to element in array

let verbList: [String] = ["hacer", "ser", "estar"]
let POVList: [String] = ["él / usted","ella / usted","ellas / ustedes","ellos / ustedes","tú","yo","nosotros",]
let correctConjugation: [[String]] = [["hace","hace","hacen","hacen","haces","hago","hacemos"], ["es","es","son","son","eres","soy","somos"], ["está","está","estan","estan","estas","estoy","estamos"]]
func randomVerb() -> Int { //creates and returns a random number for the prefix arrray
var randomVerb = Int(arc4random_uniform(3))
return randomVerb
}
func randomPrefix() -> Int { //creates and returns a random number for the verb array
var randomPrefix = Int(arc4random_uniform(7))
return randomPrefix
}
#IBAction func changeVerb(sender: AnyObject) {
Verb.text = verbList[randomVerb()]
POV.text = POVList[randomPrefix()]
userResponse.backgroundColor = UIColor.whiteColor()
userResponse.text = ""
}
#IBAction func checkResponse(sender: AnyObject) {
var userResponseA: String
userResponseA = userResponse.text
if (userResponseA == correctConjugation[randomVerb()[randomPrefix()]]){
userResponse.backgroundColor = UIColor.greenColor()
} else {
userResponse.backgroundColor = UIColor.redColor()
}
}
So I get two errors here (in the if statement in checkResponse): first, "int does not have a member named 'subscript'" and if I just take out the call for the function in the if statement I get: "'String' is not convertible to 'Mirror Disposition'"
I really have no idea why this is not working. Bear with me, as I am an Xcode noob just trying to get a better grade in spanish.
Very close - just need to have your subscripts separated:
if (userResponseA == correctConjugation[randomVerb()][randomPrefix()]) {
// ...
}
When working with an array of arrays (in this case correctConjugation), each subscript takes you one level down.
For the other issue, you want a couple variables to hold the current verb and prefix indexes:
class VC: UIViewController {
// list declarations here
var verbIndex = 0
var povIndex = 0
#IBAction func changeVerb(sender: AnyObject) {
verbIndex = randomVerb()
povIndex = randomPrefix()
Verb.text = verbList[verbIndex]
POV.text = POVList[povIndex]
userResponse.backgroundColor = UIColor.whiteColor()
userResponse.text = ""
}
#IBAction func checkResponse(sender: AnyObject) {
var userResponseA = userResponse.text
if (userResponseA == correctConjugation[verbIndex][povIndex]){
userResponse.backgroundColor = UIColor.greenColor()
} else {
userResponse.backgroundColor = UIColor.redColor()
}
}
}

Resources