2014-09-18 94 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