我在同步两个UISegments的值时遇到了问题。假设第一个UISegment根据第二个UISegment(位于不同的ViewController中)的值进行更新,然后根据第二个ViewController中选择的内容更新其自己的段中的值。但是,值不会传输到第一个UISegment,这意味着即使我使用默认值和存储键,也不会存储标题和值。
的ViewController
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var billField: UITextField!
@IBOutlet weak var tipController: UISegmentedControl!
@IBOutlet weak var splitController: UISegmentedControl!
@IBOutlet weak var splitLabel: UILabel!
let defaults = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
defaults.synchronize()
billField.becomeFirstResponder()
billField.text = String(defaults.double(forKey: "bill_value"))
print(tipController.selectedSegmentIndex)
if billField.text == "" || (billField.text == nil) {
billField.placeholder = String(0.00)
}
billField.becomeFirstResponder()
tipController.selectedSegmentIndex = defaults.integer(forKey: "default_tip_index")
}
override func viewWillAppear(_ animated: Bool) {
tipController.selectedSegmentIndex = defaults.integer(forKey: "default_tip_index")
}
@IBAction func onTap(_ sender: Any) {
view.endEditing(true)
}
@IBAction func calculateTip(_ sender: Any) {
let tipPercentages = [0.18, 0.20, 0.25]
let splitNumbers = [1,2,3,4]
let bill = Double(billField.text!) ?? 0 //converts bill to double
defaults.set(bill, forKey: "bill_value") //Saves last bill input
let tip = bill * tipPercentages[tipController.selectedSegmentIndex]
let total = bill + tip
tipLabel.text = String(format: "$%.2f", tip)
totalLabel.text = String(format: "$%.2f", total)
splitLabel.text = String(format: "$%.2f", total/Double((splitNumbers[splitController.selectedSegmentIndex])))
}
}
SettingsViewController
class SettingsViewController: UIViewController {
var tipPercentageIndex:Int!
@IBOutlet weak var settingsTipController: UISegmentedControl!
let defaults = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
let selectedDefaultPercent = defaults.integer(forKey: "default_tip_index")
settingsTipController.selectedSegmentIndex = selectedDefaultPercent
}
@IBAction func tipPercent(_ sender: Any) {
defaults.set(settingsTipController.selectedSegmentIndex, forKey: "default_tip_index")
defaults.synchronize()
}
@IBAction func splitNumber(_ sender: Any) {
}
@IBAction func Back(_ sender: Any) {
self.performSegue(withIdentifier: "Tippy2", sender: self)
}
}
总的来说,这个简单的应用程序计算提示并在访问settingsViewController时更新第一个UISegment。