尝试将多个Uitextfields添加为整数

时间:2019-01-31 18:39:41

标签: ios swift uitextfield userdefaults

我无法将Uitextfields转换为整数。我正在尝试将它们相加以获得洞2和洞3的总分?你们有什么想法吗?我试图INT(hole.text)和许多其它的变化,但一直收到错误。

//
//  ViewController.swift
//  Savetext5
//
//  Created by Brendan Berkowitz on 1/31/19.
//  Copyright © 2019 Brendan Berkowitz. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    //hole one
    @IBOutlet weak var playername: UITextField!

    @IBAction func saveButton(_ sender: Any) {
        UserDefaults.standard.set(playername.text, forKey: "playonename")}
    @IBAction func deleteButton(_ sender: Any) {
        UserDefaults.standard.removeObject(forKey: "playonename")}

    // hole 2
    @IBOutlet weak var holetwo: UITextField!

    @IBAction func saveButton2(_ sender: Any) {
        UserDefaults.standard.set(holetwo.text, forKey: "holetwo")}
    @IBAction func deleteButton2(_ sender: Any) {
        UserDefaults.standard.removeObject(forKey: "holetwo")}

    // hole 3

    @IBOutlet weak var holethree: UITextField!
    @IBAction func savebutton3(_ sender: Any) {UserDefaults.standard.set(holethree.text, forKey: "holethree")}
    @IBAction func deletebutton3(_ sender: Any) {UserDefaults.standard.removeObject(forKey: "holethree")}


    override func viewDidLoad() {
        super.viewDidLoad()

        //hole one
        let savedName = UserDefaults.standard.object(forKey: "playonename")
        if let playeronename = savedName as?  String {
            playername.text = playeronename 
        }

        // Hole two
        let savedholetwoname = UserDefaults.standard.object(forKey: "holetwo")
        if let holetwoname = savedholetwoname as? String { 
            holetwo.text = holetwoname
        }

        // hole three
        let savedholethreename = UserDefaults.standard.object(forKey: "holethree")
        if let holethreename = savedholethreename as? String {
            holethree.text = holethreename
        }   
    }
}

2 个答案:

答案 0 :(得分:0)

您可以选择许多解决方案。但是,在将文本字段的文本转换为Int之前,应进行一些检查和处理 例如,文字是否为空?文本格式有效吗?

// define utility function

extension UITextField {
  var textToInt: Int {
     // return 0 as default value
     return Int(text ?? "0") ?? 0
  }
}

class ViewController: UIViewController {
   func totalScore() -> Int {
      return holetwo.textToInt + holethreename.textToInt
   }
}

答案 1 :(得分:-1)

javac