protocol LightRedViewControllerDelegate {
func setColor(colorType:String)
}
class服從的協定:
class LightRedViewController: UIViewController,UIPickerViewDataSource,UIPickerViewDelegate
//專門用來接受第一個畫面所傳資料的屬性
//Optional String不用初始化
var inforFromViewOne:String?
//新增屬性
//delegate的值為ViewController(第一個畫面)
var delegate:LightRedViewControllerDelegate?
//PickerView顯示的資料
let colorArray = ["red","green","blue"]
viewDidLoad:
//將第一個畫面傳來的inforFromViewOne設定給myLable顯示
myLabel.text = inforFromViewOne
//服從協定
myPickerView.dataSource = self
myPickerView.delegate = self
PickerView的設定:
//顯示橫列的數量
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
//顯示直列的數量
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return colorArray.count
}
//顯示的內容
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return colorArray[row]
}
設置返回按鈕:
@IBAction func backtoView1(_ sender: UIButton) {
let colorNumber = myPickerView.selectedRow(inComponent: 0)
let color = colorArray[colorNumber]
//將顏色字串當作參數呼叫delegate,執行setColor方法
delegate?.setColor(colorType: color)
navigationController?.popViewController(animated: true)
}