将数据传回UIPickerView
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将数据传回UIPickerView相关的知识,希望对你有一定的参考价值。
我正在创建计时器应用,我希望用户能够编辑现有计时器。例如,当用户单击特定的计时器时,他可以编辑小时,分钟和秒,我最初是从UIPickerView中获得的。
我正在使用此代码来获取新计时器的小时,分钟和秒:
var hour: Int = 0
var minutes: Int = 0
var seconds: Int = 0
var name: String = ""
var totalSeconds: Int {
return hour * 3600 + minutes * 60 + seconds
}
}
extension TimerSelectViewController: UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 3
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
switch component {
case 0:
return 25
case 1, 2:
return 60
default:
return 0
}
}
func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
return pickerView.frame.size.width/4
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
switch component {
case 0:
return "(row) hr"
case 1:
return "(row) min"
case 2:
return "(row) sec"
default:
return ""
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
switch component {
case 0:
hour = row
case 1:
minutes = row
case 2:
seconds = row
default:
break;
}
}
但是当用户想要编辑计时器而不创建新计时器时,如何将数据传递回UIPickerView?
答案
UIPickerView有一种用于预选择行的方法:https://developer.apple.com/documentation/uikit/uipickerview/1614382-selectrow
例如:
let picker = UIPickerView()
// 14:00:00 or 2:00:00 PM, add more select commands as needed
picker.selectRow(14, inComponent: 0, animated: false)
以上是关于将数据传回UIPickerView的主要内容,如果未能解决你的问题,请参考以下文章