ios - 3 组件UIPickerView 制作3位数值

标签 ios swift uipickerview

我有一个 3 组件 UIPickerWheel,允许用户选择 0-199 之间的 3 位数字,我希望最终将该数字存储为变量。

当我测试构建应用程序时,数百列按其应有的方式工作。然而,我的个位数列以某种方式链接到我的十位列,当我更新个位数列时,控制台会打印该数字的十位列版本(001 打印 10 而不是 1)

是什么导致了这个问题?我该如何解决它?

提前致谢!

编辑:我更新了我的数组并从个位数列中删除“0”似乎是一个快速解决方案,但我仍然很好奇为什么这是一个问题。

import UIKit

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

    @IBOutlet weak var numberPicker: UIPickerView!

    var pickerData = [[String]]()

    var hundredsColumn = "0"
    var tensColumn = "0"
    var singleDigits = "0"

    override func viewDidLoad() {
        super.viewDidLoad()

        self.numberPicker.delegate = self
        self.numberPicker.dataSource = self

        pickerData = [
            ["0","1"],
            ["0","1","2","3","4","5","6","7","8","9"],
//Original  ["0","1","2","3","4","5","6","7","8","9"],
            ["1","2","3","4","5","6","7","8","9"],
        ]

    }

    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 3
    }

    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return pickerData[component].count
    }

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

    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if pickerData[component] == pickerData[0] {
            hundredsColumn = pickerData[0][row]
        }
        else if pickerData[component] == pickerData[1] {
            tensColumn = pickerData[1][row]
        }
        else {
            singleDigits = pickerData[component][row]
        }

        let total = (Int(hundredsColumn)! * 100 + (Int(tensColumn)! * 10) + (Int(singleDigits)! * 1)
        print(total)
    }
}

最佳答案

这是有效的,不需要将字符串转换为整数并直接添加字符串即可将其转换为整数

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
    {
        if pickerData[component] == pickerData[0] {
            hundredsColumn = pickerData[0][row]
        }
        else if pickerData[component] == pickerData[1] {
            tensColumn = pickerData[1][row]
        }
        else {
            singleDigits = pickerData[component][row]
        }
        let totalIs = hundredsColumn + tensColumn + singleDigits
        print("\(totalIs)")
    }

关于ios - 3 组件UIPickerView 制作3位数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36071706/

相关文章:

ios - 避免 uiwebview 过多的垂直滚动

iOS 委托(delegate)方法在需要时没有被调用

swift - 使用 Sprite Kit 在 Swift 中隐藏或显示 Google Ad View

ios - 如何将多张图片存储到 Parse 中的单个列?

ios - 缩放 UIImageView 并在缩放范围内移动

ios - 如何在不使用 UIImagePickerController 的情况下使用内置 iOS 相机

ios - 如何使用具有多个对象(几何体)的场景文件中的几何体?

iphone - 显示图像和字符串的 UIPIckerView

Swift 动态 UIPickerView

ios - 无法在选择器 View 中滚动的情况下选择默认值