【发布时间】:2017-03-29 07:45:53
【问题描述】:
目前,我正在以编程方式在cellForRowAt 中创建UITextField 和UIPickerView。如果我将UITextField 连接到IBOutlet,我可以轻松更新didSelectRow 中选定的UIPickerView 值。
但是,我需要以编程方式创建 UITextField,并应用 AutoLayout 约束。
但是,我不知道如何更新 UITextField,因为我在 UIPickerView's didSelectRow 函数中没有引用它,因为它是在 cellForRowAt 中以编程方式创建的,如下所示:
var testing: [String] = []
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
// Dequeue the cell to load data
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
if indexPath.section == 2
{
let wearsPickerView: UIPickerView = UIPickerView()
wearsPickerView.delegate = self
wearsPickerView.dataSource = self
let textField: UITextField = UITextField()
textField.translatesAutoresizingMaskIntoConstraints = false
textField.textColor = UIColor.black
textField.text = "Test"
textField.delegate = self
textField.inputView = wearsPickerView
cell.contentView.addSubview(textField)
let leadingConstraint = NSLayoutConstraint(item: cell.contentView, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: textField, attribute: NSLayoutAttribute.leading, multiplier: 1.0, constant: 0)
let trailingConstraint = NSLayoutConstraint(item: cell.contentView, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: textField, attribute: NSLayoutAttribute.trailing, multiplier: 1.0, constant: 0)
cell.contentView.addConstraint(leadingConstraint)
cell.contentView.addConstraint(trailingConstraint)
let topConstraint = NSLayoutConstraint(item: cell.contentView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: textField, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 0)
let bottomConstraint = NSLayoutConstraint(item: cell.contentView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: textField, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: 0)
cell.contentView.addConstraint(topConstraint)
cell.contentView.addConstraint(bottomConstraint)
}
return cell
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
textField.resignFirstResponder()
return true
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
{
return testing.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
{
return testing[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
// How to update UITextField string?
}
【问题讨论】:
-
是您的表格视图静态,例如您的输入文本字段总是在第 2 节,索引 0?您的单元格是 UITableViewCell 子类还是仅仅是 UITableViewCell?
标签: ios swift swift3 uitextfield uipickerview