Swift:UIpickerView在UIlabel上返回数字

时间:2017-09-09 00:28:23

标签: ios swift uilabel uipickerview

我的UIpickerView中有3个组件,我想返回UIpickerView上显示的所有3个数字,但它只返回已选择的最后一个数字。换句话说,UIlabel只显示一个数字。这是我到目前为止所拥有的

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

@IBOutlet weak var label: UILabel!
@IBOutlet weak var pickerView: UIPickerView!

let numbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]

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

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

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return numbers.count
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    label.text = numbers[row]
}

3 个答案:

答案 0 :(得分:1)

请检查:

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

    let val1 = numbers[pickerView.selectedRow(inComponent: 0)]
    let val2 = numbers[pickerView.selectedRow(inComponent: 1)]
    let val3 = numbers[pickerView.selectedRow(inComponent: 2)]

    label.text = "\(val1) \(val2) \(val3)"
}

答案 1 :(得分:0)

final int CHUNK_SIZE = 50; for (int i = 0; i < idsVideos.size(); i += CHUNK_SIZE) { List<String> chunk = idsVideos.subList(i, Math.min(i + CHUNK_SIZE, idsVideos.size())); .. } 只显示一位数,因为您只是告诉它显示最近选择的号码。相反,您需要询问UILabel每个组件所选索引的内容。像

这样的东西
UIPickerView

答案 2 :(得分:0)

由于选择器视图包含多个组件,因此在<link href="https://cdnjs.cloudflare.com/ajax/libs/rangeslider.js/2.3.1/rangeslider.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/rangeslider.js/2.3.0/rangeslider.min.js"></script> <h1>Programmatic value changes</h1> <br> <br> <input type="range" id="js-amount-range" value="0" min="0" max="100"> <br> <br> <input type="number" id="js-amount-input" value="0" min="0" max="100"></input> <span>.00 $</span>委托方法中实施label.text = numbers[row]是不够的,这导致您在问题中提到 - 阅读 第一个组件的值。

为了更清楚,如果您尝试将didSelectRow更改为label.text = numbers[row],您应该注意到标签文本将是选择器视图的第二个值,因为selectedRow(inComponent:) - label.text = numbers[pickerView.selectedRow(inComponent: 1)]参数为:

  

标识了选择器视图组件的零索引编号

粗略地说,如果你想从所有组件中获取值,你必须确定要读取的组件,在你的情况下是三个组件。

我认为最简单的 static 方法是:

component

但是可以肯定的是,这样的事情 - 使用Higher-order functions - 会更受欢迎(主要是@Kevin Ballard's answer的相同逻辑,只有很简单的改进):

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    label.text = "\(numbers[pickerView.selectedRow(inComponent: 0)])\(numbers[pickerView.selectedRow(inComponent: 1)])\(numbers[pickerView.selectedRow(inComponent: 2)])"
}