我快要瘋了... 我得到了一個具有自定義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
}
}
偉大的作品。不知道awakeFromNib部分;) – Timm 2014-09-18 21:29:36