2014-09-18 96 views
1

我快要瘋了... 我得到了一個具有自定義UITableViewCell的UITableViewController。 UITableView單元包含一個通過Interface Builder連接的UITextfield。Swift:在自定義TableViewCell上設置UITextfieldDelegate

儘管我可以在不設置委託的情況下編輯UITextfield,但我無法讓鍵盤消失。當我嘗試設置UITextField的代理時,應用程序崩潰並顯示錯誤。

fatal error: unexpectedly found nil while unwrapping an Optional value

因爲我通過IB設置TextFiled,我沒有用的UITextField(創建),是吧?我錯過了什麼?

MainTableViewController:

import UIKit 

class MainTableViewController: UITableViewController { 

    override func viewDidLoad() { 
    super.viewDidLoad() 
    } 

    override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
    } 

    // MARK: - Table view data source 

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    // Return the number of sections. 
    return 1 
    } 

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    // Return the number of rows in the section. 
    return 5 
    } 


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("CounterCell", forIndexPath: indexPath) as CounterTableViewCell 
    // Configure the cell... 

    return cell 
    } 
} 

定製TableViewCell:

import UIKit 

class CounterTableViewCell: UITableViewCell, UITextFieldDelegate { 

    // ================================================== 
    // MARK: - Variables 

    // ================================================== 
    // MARK: - Outlets & Actions 
    @IBOutlet weak var tfName: UITextField! 

    // ================================================== 
    // MARK: - Lifecycle 
    required init(coder aDecoder: NSCoder) { 
    super.init(coder: aDecoder) 
    NSLog("init coder") 

    // ERROR HERE: fatal error: unexpectedly found nil while unwrapping an Optional value 
    tfName.delegate = self 
    } 

    override func awakeFromNib() { 
    super.awakeFromNib() 
    // Initialization code 
    } 

    // ================================================== 
    // MARK: - UITableViewCell methods 
    override func setSelected(selected: Bool, animated: Bool) { 
    super.setSelected(selected, animated: animated) 

    // Configure the view for the selected state 
    } 

    // MARK: - UITextFieldDelegate 
    func textFieldShouldReturn(textField: UITextField) -> Bool { 
    textField.resignFirstResponder() 
    return true 
    } 

    func textFieldShouldBeginEditing(textField: UITextField) -> Bool { 
    return true; 
    } 

    func textFieldDidEndEditing(textField: UITextField) { 
    // do nothing yet 
    } 
} 

回答

2

既然你在Interface Builder創建的文本字段,你爲什麼不連接delegate財產有太多?只需控制 - 從文本字段拖動到您的視圖控制器,並從彈出菜單中選擇代表

您不能在init(coder:)中設置文本字段的委託,因爲此時文本字段尚未被解除存檔。如果您想以編程方式設置此項,請嘗試在awakeFromNib中執行此操作,該操作在之後保證稱爲,然後將該筆尖中的所有對象都解除存檔。

+0

偉大的作品。不知道awakeFromNib部分;) – Timm 2014-09-18 21:29:36

相關問題