[英]How can I take the text from UITextFields in UITableViewCells in a UITableView and put them into an array (Swift 3)?
我正在制作一个包含UITableView的计算器应用程序,该应用程序允许用户在单击计算器UIButton进行计算之前输入变量。 我想使用UITableView而不是仅计划UITextFields的原因是因为我的应用程序包含许多不同的计算,这意味着UITableViewCells的数量根据用户的选择而变化。
我希望找到一种方法,只要按下计算器的UIButton即可获得可见的UITextField值的数组。 UITableView类似乎更适合于将数据输入单元格而不是获取数据。 我可以使用其他方法吗? 我正在使用一个带有Swift 3文件的情节提要。
由于您未提供一些示例代码,因此我将在此处进行很多假设。
假设您使用的是其中包含UITableView
的UIViewController
class CalculatorViewController
@IBOutlet var tableView: UITableView!
var values: [Double] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
}
}
现在您有了一个基本的viewController,但是编译器会说CalculatorViewController不符合UITableViewDataSource
和UITableViewDelegate
。 我们修复一下
extension CalculatorViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
// return your number of sections, let say it's one
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Let's say you only have 3 cells at the moment
return 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "YourCustomInputFieldCell") as! YourCustomInputFieldCell
return cell
}
}
让我们修复UITableViewDelegate
错误
extension CalculatorViewController: UITableViewDelegate {
// This one gets called each time a cell will be displayed (as it says)
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if let cell = cell as? YourCustomInputTextField {
// I assume that you expose your cell's input field
// By setting a tag on the input field you can
// distinguish it from other inputs
cell.input.tag = indexPath.row
cell.input.delegate = self
}
}
}
再次,编译器会抱怨CalculatorViewController
不符合UITextFieldDelegate
。 让我们也修复它。
extension CalculatorViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Here you can check the tag of the textField
// and update the values array accordingly
// You should probably convert the string that you get to
// the number format that you want
return true
}
}
希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.