我想在段控制中使用pickerview,这样当我切换段时,拾取器数据也会发生变化。这是我的代码:

时间:2017-02-09 18:34:34

标签: ios iphone swift swift3

// IBAction用于段控制以更改标签中的值

@IBAction func changeValueSC(_ sender: Any) {

    switch segmentControl.selectedSegmentIndex {
    case 0:
        questionLabel.text = "HAS FOOD INTAKE DECLINED OVER THE PAST 3 MONTHS, DUE TO LOSS OF APPETITE, DIGESTIVE PROBLEMS, CHEWING OR SWALLOWING DIFFICULTIES ?"
        //[self, pickerView(pickerView, titleForRow: 5, forComponent: 1)!] as [Any]
    case 1:
        questionLabel.text = "WEIGHT LOSS DURING THE PAST 3 MONTHS ?"
    case 2:
        questionLabel.text = "MOBILITY"
    case 3:
        questionLabel.text = "HAVE YOU SUFFERED PSYCHOLOGICAL STRESS OR ACUTE DISEASE IN THE PAST 3 MONTHS ?"
    case 4:
        questionLabel.text = "NUEROPSYCHOLOGICAL PROBLEMS"

    default:
        break
    }

}

// pickerview的强制方法

public func numberOfComponents(in pickerView: UIPickerView) -> Int{

    return 1   
}

// options1,options2 ..... options5是字符串类型数组

public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{

    switch segmentControl.selectedSegmentIndex {
    case 0:
        return options1.count
    case 1:
        return options2.count
    case 2:
        return options3.count
    case 3:
        return options4.count
    case 4:
        return options5.count
    default:
        return 0
    }
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?{



    switch segmentControl.selectedSegmentIndex {
    case 0:
        return options1[row]
    case 1:
        return options2[row]
    case 2:
        return options3[row]
    case 3:
        return options4[row]
    case 4:
        return options5[row]
    default:
        return ""
    }

}

当我更改细分时标签数据正在变化但是选择器视图中没有显示数据

screenshot of the view controller

2 个答案:

答案 0 :(得分:1)

你必须告诉选择器视图数据已经改变,它应该刷新它的一些(或全部)组件:

@IBAction func changeValueSC(_ sender: Any) {

    // ... same as before

    self.pickerView.reloadComponent(0)
    // or: reloadAllComponents()
}

答案 1 :(得分:0)

changeValueSC功能中,您需要致电self.pickerView.reloadAllComponents()