2015-06-21 58 views
0

我有一個文本框,當在文本框中鍵入內容並按下鍵盤上的「返回」時,鍵盤應該隱藏。但事實並非如此..返回按下時功能未運行

這裏是我使用的代碼:

import UIKit 

class EditTableViewController: UITableViewController, UITextFieldDelegate { 

var product: Product? 


@IBOutlet weak var productImageView: UIImageView! 
@IBOutlet weak var ProductDescriptionTextView: UITextView! 
@IBOutlet weak var productTitleLabel: UITextField! 



override func viewDidLoad() { 
    super.viewDidLoad() 
    println("loaded") 
    productImageView.image = product?.image 
    productTitleLabel.text = product?.title 
    ProductDescriptionTextView.text = product?.description 
} 

override func viewWillDisappear(animated: Bool) { 
    product?.title = productTitleLabel.text 
    product?.description = ProductDescriptionTextView.text 
    product?.image = productImageView.image! 
} 

func textFieldShouldReturn(textField: UITextField) -> Bool // called when 'return' key pressed. return NO to ignore. 
{ 
println("return") 
return true 
} 
} 

在控制檯中我得到的「裝」,但是當我按在文本框的回報,我不明白「返回「

怎麼回事?

+0

您需要設置文本字段的委託,如果你還沒有在你的故事板 – Paulw11

+0

這樣做您在隱藏鍵盤的'textFieldShouldReturn'函數中沒有任何代碼。它不會自動發生。如果這是你想要的,你需要隱藏它。 – rmaddy

回答

0

你忘了給出UITextField的委託設置爲您的視圖控制器(個體經營) productTitleLabel.delegate = self - 也注意到,你應該正確地命名變量,以避免混亂(productTitleTextField,而不是一個「標籤」後綴)

或者代之以以編程方式執行此操作,可以在故事板中按Ctrl-從textView拖動到故事板中的視圖控制器,然後在彈出菜單上選擇委託。

first

second

然後,讓你的視圖控制器符合UITextFieldDelegate協議:

class EditTableViewController: UITableViewController, UITextFieldDelegate { 
.... 
    func textFieldShouldReturn(textField: UITextField) -> Bool { 
     if textField == productTitleLabel { 
      textField.resignFirstResponder() 
     } 
     return true 
    } 
} 
0

在你viewDidLoad方法你必須添加:

productTitleLabel.delegate = self 

並更新textFieldShouldReturn這樣的:

func textFieldShouldReturn(textField: UITextField) -> Bool // called when 'return' key pressed. return NO to ignore. 
{ 
    productTitleLabel.resignFirstResponder() 
    return true 
} 

,它會隱藏你的鍵盤當回車鍵按下。

+0

解決了,謝謝! – sdd