我只是试图从TableView中检索所有文本字段值。它为11个案例中的10个工作。我尝试了以下方法:
let journeyIDTextField = tableView.cellForRow(at: NSIndexPath(row: 0, section: 1) as IndexPath) as! InputTableViewCell
journeyID = journeyIDTextField.cellInputTextfield.text!
当我将部分从1-10更改为一切正常时,第0部分导致错误。致命错误:展开一个可选值时意外发现nil
因此,我尝试查看IndexPath(0,0)是否存在文本字段。
print(section.description, indexPath.row, indexPath.section)
Result: Description 0 0
所以肯定在0,0处有一个文本字段。我不知道该怎么办,特别是因为它在另一个ViewController上可以正常工作。
有什么想法吗?
最好,蒂莫
func numberOfSections(in tableView: UITableView) -> Int {
return JourneySection.allCases.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierInputCell, for: indexPath) as! InputTableViewCell
guard let section = JourneySection(rawValue: indexPath.section) else { return UITableViewCell() }
cell.cellInputTextfield.placeholder = section.description
print(section.description, indexPath.row, indexPath.section)
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
这是我的手机:导入UIKit
class InputTableViewCell: UITableViewCell {
let cellInputTextfield: UITextField = {
let cellInputTextfield = UITextField()
cellInputTextfield.textColor = .black
cellInputTextfield.sizeToFit()
return cellInputTextfield
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .default, reuseIdentifier: reuseIdentifier)
cellInputTextfield.frame = CGRect(x: 20, y: 0, width: self.frame.width, height: 60)
cellInputTextfield.font = UIFont.systemFont(ofSize: 15)
self.contentView.addSubview(cellInputTextfield)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
enum JourneySection:Int, CaseIterable, CustomStringConvertible{
case Description
case ID
case Confirmation
case Destination
case DestinationDate
case DestinationTime
case Arrival
case ArrivalDate
case ArrivalTime
case PriceTotal
case Companions
var description: String {
switch self {
case .Description: return "Description"
case .ID: return "ID f.ex. Flight Number"
case .Confirmation: return "Confirmation No."
case .Destination: return "Destination"
case .DestinationDate: return "Destination Date, like DD-MM-YYYY"
case .DestinationTime: return "Destination Time, like hh-mm"
case .Arrival: return "Arrival"
case .ArrivalDate: return "Arrival Date, like DD-MM-YYYY"
case .ArrivalTime: return "Arrival Time, like hh-mm"
case .PriceTotal: return "Total Price"
case .Companions: return " No. Of Companions"
}
}
}
我认为一个问题是,当journeyIDTextField.cellInputTextfield.text
等于nil
时,您将被强制展开。我看到的另一个潜在问题是,由于单元重用,滚动时您的文本字段文本将被擦除。有关在重用单元格中正确使用文本字段的信息,请参见this question。
谢谢,提到的问题解决了我的问题!
您从不想“从单元格中获取文本”。单元格被重用,因此当您滚动文本字段时,Section: 0 Row: 0
中的was