我有一个UITableView,UITableViewCell中有5个文本字段。
我必须分配UITextFieldDelegate,并希望在textField上创建边框线。我从cellForRowAtIndexPath调用函数createBorderLine,但它抛出了一个错误(致命错误:在展开可选值时意外找到nil)。
以下是我的代码:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let identifier = "EditProductCell"

        var editProductCell = tableView.dequeueReusableCell(withIdentifier: identifier) as? EditProductCell
        if(editProductCell == nil)
        {
            let nib:Array = Bundle.main.loadNibNamed("EditProductCell", owner: self, options: nil)!
            editProductCell = nib[0] as? EditProductCell

            //Call Create Border Line function.
            self.createBorderLine()
        }
}

下面是我的createBorderLine函数:
func createBorderLine()
{
    let index : NSIndexPath = NSIndexPath(row: 0, section: 0)
    let tCell : EditProductCell = self.tableView.cellForRow(at: index as IndexPath) as! EditProductCell

    tCell.InvoiceDate.delegate = self
    tCell.InvoiceNumber.delegate = self
    tCell.modelNumber.delegate = self
    tCell.productName.delegate = self
    tCell.serialNumber.delegate = self
    tCell.viewWarrentyDate.isHidden = true


    setBottomBorder(textField: tCell.InvoiceDate, width: 0.8,color : UIColor.lightGray)
    setBottomBorder(textField: tCell.InvoiceNumber, width: 0.8,color : UIColor.lightGray)
    setBottomBorder(textField: tCell.modelNumber, width: 0.8,color : UIColor.lightGray)
    setBottomBorder(textField: tCell.productName, width: 0.4,color : UIColor.lightGray)
    setBottomBorder(textField: tCell.serialNumber, width: 0.4,color : UIColor.lightGray)
}

我能做什么?为什么会出错?

最佳答案

为什么每次在createBorderLine中为行0和节0创建indexpath。只需在createBorderLine中传递单元格引用

self.createBorderLine(editProductCell)

createBorderLine函数中
 func createBorderLine(tCell: EditProductCell)
 {

tCell.InvoiceDate.delegate = self
tCell.InvoiceNumber.delegate = self
tCell.modelNumber.delegate = self
tCell.productName.delegate = self
tCell.serialNumber.delegate = self
tCell.viewWarrentyDate.isHidden = true


setBottomBorder(textField: tCell.InvoiceDate, width: 0.8,color : UIColor.lightGray)
setBottomBorder(textField: tCell.InvoiceNumber, width: 0.8,color : UIColor.lightGray)
setBottomBorder(textField: tCell.modelNumber, width: 0.8,color : UIColor.lightGray)
setBottomBorder(textField: tCell.productName, width: 0.4,color : UIColor.lightGray)
setBottomBorder(textField: tCell.serialNumber, width: 0.4,color : UIColor.lightGray)

}

您应该将createBorderLine放入createBorderLine类,而不是在Controller类中创建EditProductCell。并直接通过EditProductCell对象引用调用。

10-04 11:34