2017-04-17 62 views
1

我的問題是我在可擴展表格視圖內部有一個文本框,由cellDescription plist指定。在此表格視圖中,當地址部分展開時,會彈出一個文本字段,用戶可以在其中輸入地址。用戶必須在鍵盤上按回車鍵(或輸入)才能保存地址。我想知道是否有一種方法可以檢測文本字段中的變化,這種變化可以不斷更新文本字段的值,這樣用戶就不必輸入return來保存地址。下面是我的代碼目前的結構,但我很困惑,因爲文本字段不在常規視圖控制器內,而是在外部xib文件中。Swift在.xib文件中檢測文本字段中的更改

func configureTableView() { 
    tblExpandable.delegate = self 
    tblExpandable.dataSource = self 
    tblExpandable.tableFooterView = UIView(frame: CGRect.zero) 
    tblExpandable.register(UINib(nibName: "TextfieldCell", bundle: nil), forCellReuseIdentifier: "idCellTextfield") 

} 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let currentCellDescriptor = getCellDescriptorForIndexPath(indexPath) 
    let cell = tableView.dequeueReusableCell(withIdentifier: currentCellDescriptor["cellIdentifier"] as! String, for: indexPath) as! CustomCell 


    if currentCellDescriptor["cellIdentifier"] as! String == "idCellTextfield" { 
     cell.textField.placeholder = currentCellDescriptor["primaryTitle"] as? String 
     valueOfInterest = cell.textField.text! 

    } 


    cell.delegate = self 

    return cell 
} 

func textfieldTextWasChanged(_ newText: String, parentCell: CustomCell) { 
    let parentCellIndexPath = tblExpandable.indexPath(for: parentCell) 

    var address = "" 

    address = "\(newText)" 


    ((cellDescriptors[0] as! NSMutableArray)[11] as AnyObject).setValue(address, forKey: "primaryTitle") 
    location = (((cellDescriptors[0]) as! NSMutableArray)[11] as! NSDictionary)["primaryTitle"]! as! String 
    tblExpandable.reloadData() 
} 

回答

1

在這裏,您的CustomCell中有文本字段。所以設置文本字段的出口在CustomCell類如:

@IBOutlet weak var textField:UITextField! 

然後設置CustomCell類作爲文本框的委託,並實現文本字段的所需委託方法來檢測在TextField中的值的變化。

+0

如何將CustomCell類設置爲textField的委託,因爲此swift文件沒有「override func viewDidLoad(){}」? – Kevin

+0

爲什麼您需要viewDidLoad()方法來設置委託。您可以從自定義單元類的xib文件或awakeFromNib()方法中設置委託。 –

+0

試圖在awakeFromNib()中設置如下代理:「textField.delegate = self」在模擬器中運行時導致錯誤:致命錯誤:意外地在解包可選值時發現nil。我沒有正確設置委託嗎? – Kevin