由于您没有提供一些示例代码,我将在这里做很多假设。
假设您使用的是 UIViewController,其中包含 UITableView
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
}
}
希望对你有帮助。