如何在uialertview中添加uipickerview swift 3
问题描述:
Swift 3 iOS 10:我想在UIAlertView
中添加UIPickerView
,这样我就可以选择item并将其值设置为textField。我可以用UIView
做到这一点,但我想以更好和自然的方式改善它。是否有可能做到这一点或任何出路?如何在uialertview中添加uipickerview swift 3
提前致谢!
这是我做了什么,
答
虽然苹果公司建议我们不这样做,你可以的确可以将选取器视图添加到您的警报视图控制器。 UIAlertViewController
除了普通的视图控制器以外没有任何魔术。所有你需要做的就是显示标题文本和大量新行(即“选择\ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n”),以增加提醒高度,然后致电alertViewController.addSubview(datePicker)
但是,问题是为什么您需要编写额外的代码来操纵警报视图控制器并处理要设置值的文本字段?这是另一种更容易维护和实施的方法。
首先创建您的选取器视图并对其进行配置。
let picker = UIPickerView()
picker.delegate = self
picker.dateSource = self
// configure
然后为每个文本字段,只需拨打这个
tf1.tag = 1
tf2.tag = 2
tf3.tag = 3
tf1.delegate = self
tf2.delegate = self
tf3.delegate = self
tf1.inputView = picker
tf2.inputView = picker
tf3.inputView = picker
不在你的文本字段的委托方法,存储该文本字段用户点击并重新加载选择器视图数据
var tfTag = 0
func textFieldDidBeginEditing(_ textField: UITextField) {
tfTag = textField.tag
picker.reloadAllComponents()
}
最后,在所有选择器视图数据源或委托方法中,从每个文本字段的唯一标签编号加载不同的一组数据库
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if tfTag == 0 {
if component == 0 {
return "1"
}else if component == 1 {
return "2"
}else if component == 2 {
return "3"
}else{
return "4"
}
}else if tfTag == 1 {
//...
}else{
//...
}
}
谢谢你,这是我想要的。但我有这个问题。我无法使用uipickerview时,我有多个/许多文本域 –
@EKChhuon更新 –
非常感谢,我知道了 –