为用户(Swift)保存UIPickerView选项(货币选择)?

时间:2018-03-20 13:41:09

标签: ios swift uipickerview

我的应用在打开应用时默认显示以英镑为单位的价格。我可以更改货币但是当应用程序关闭时它会恢复为£。如何使选择器上的用户选择覆盖默认货币并保存直到再次更改?我认为它正在使用UserDefaults?我还没弄清楚。

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

//    let defaults = UserDefaults.standard

let baseURL = "https://apiv2.bitcoinaverage.com/indices/global/ticker/BTC" // API
let currencyArray = ["AUD", "BRL","CAD","CNY","EUR","GBP","HKD","IDR","ILS","INR","JPY","MXN","NOK","NZD","PLN","RON","RUB","SEK","SGD","USD","ZAR"] // List of currencies
let currencySymbolArray = ["$", "R$", "$", "¥", "€", "£", "$", "Rp", "₪", "₹", "¥", "$", "kr", "$", "zł", "lei", "₽", "kr", "$", "$", "R"]           // Currency symbols
var currencySelected = ""
var finalURL = ""


// Pre-setup IBOutlets
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var currencyPicker: UIPickerView!
@IBOutlet weak var doneButton: UIButton!

@IBAction func doneButton(_ sender: UIButton) {

    currencyPicker.isHidden = true
    doneButton.isHidden = true

}



override func viewDidLoad() {
    super.viewDidLoad()




    currencyPicker.delegate = self
    currencyPicker.dataSource = self

    currencyPicker.selectRow(5, inComponent:0, animated:false) // Select default currency choice to £


    // Print out the default row price 

    finalURL = baseURL + currencyArray[5]
    print(finalURL)
    currencySelected = currencySymbolArray[5]
    getBitcoinData(url: finalURL)

    currencyPicker.isHidden = true
    doneButton.isHidden = true

    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
    tapGesture.numberOfTapsRequired = 1
    priceLabel.isUserInteractionEnabled = true
    priceLabel.addGestureRecognizer(tapGesture)
}

@objc func handleTap(_ sender: UITapGestureRecognizer? = nil)
{
    self.currencyPicker.isHidden = false
    self.doneButton.isHidden = false



}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}




// Number of columns

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}
// Number of rows

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return currencyArray.count // Number of rows = the amount in currency array
}

// Row Title

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
   return currencyArray[row]
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    finalURL = baseURL + currencyArray[row]
    print(finalURL)
    currencySelected = currencySymbolArray[row]
    getBitcoinData(url: finalURL)

}


//MARK: - Networking
/***************************************************************/

func getBitcoinData(url: String) {

    Alamofire.request(url, method: .get)
        .responseJSON { response in
            if response.result.isSuccess {

                print("Sucess! Got the Bitcoin data.")
                let bitcoinJSON : JSON = JSON(response.result.value!)

                self.updateBitcoinData(json: bitcoinJSON)

            } else {
                print("Error: \(String(describing: response.result.error))")
                self.priceLabel.text = "Error: Check Connection"
            }
    }

}

//MARK: - JSON Parsing
/***************************************************************/

func updateBitcoinData(json : JSON) {

    if let bitcoinResult = json["ask"].double {

        priceLabel.text = currencySelected + String(bitcoinResult)
    } else {
        priceLabel.text = "Price Unavaiable"
    }
}

// let timer = Timer.scheduledTimer(timeInterval: 15, target: self, selector: #selector(self.someMethod), userInfo: nil, repeats: true)
 }

2 个答案:

答案 0 :(得分:1)

您使用以下代码行编写结果的硬编码:

currencyPicker.selectRow(5, inComponent:0, animated:false) // Select default currency choice to £

如果您想将其更改为用户设置,您可以执行以下操作。

// create class variable to hold integer
var indexedItem : Int?

// give indexedItem a value in viewDidLoad
func viewDidLoad() {
    super.viewDidLoad()
    if let num = UserDefaults.standard.integer(forKey: "Key") {
        indexedItem = num
    } else {
        indexedItem = 0
    }

}

func viewWillAppear(){
    super.viewWillAppear(animated)
    currencyPicker.selectRow(indexedItem!, inComponent:0, animated:false)
}

// create function to do save
// you could make this an @IBAction linked to a button
func doSaveButton() {
    UserDefaults.standard.set(indexedItem!, forKey: "Key")
}

// set integer in picker  didSelectRow
 indexedItem = currencyPicker.currencySymbolArray[row]

答案 1 :(得分:1)

viewDidLoad()

if let selectedCurrency = UserDefaults.standard.integer(forKey: "selectedCurrency") {
    currencyPicker.selectRow(selectedCurrency, inComponent:0, animated:false)
}
else {
    currencyPicker.selectRow(5, inComponent:0, animated:false)
}

didSelectRow

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
   UserDefaults.standard.set(row, forKey: "selectedCurrency")
}