如何从cellForRowAtIndexPath获取textField上的边框线?

时间:2016-12-29 09:58:07

标签: ios swift uitableview delegates uitextfield

我有一个UITableView,在UITableViewCell里面有5个textFields。 我必须分配UITextFieldDelegate并想在textField上创建边框线。我从cellForRowAtIndexPath调用我的函数createBorderLine但是它抛出了一个错误(致命错误:在展开Optional值时意外地发现了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)
}  

我该怎么办?为什么会出错?

1 个答案:

答案 0 :(得分:2)

为什么每次在createBorderLine中为第0行和第0部分创建索引路径。只需在createBorderLine

中传递单元格ref
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)

}  

不应在Controller类中创建createBorderLine,而应将createBorderLine放在EditProductCell类中。并通过EditProductCell对象引用

直接调用