2016-03-05 76 views
0

我在線學習了一個教程,將一個自定義工具欄和一個完成按鈕添加到鍵盤。 Xcode不會給我任何錯誤,但是當我運行我的應用程序時,我的鍵盤上沒有工具欄或完成按鈕。我在代碼中做了什麼錯誤?謝謝!爲什麼我的代碼不會將工具欄和完成按鈕添加到我的鍵盤?

這裏是我的代碼 -

import UIKit 

class ViewController: UIViewController, UITextFieldDelegate { 

@IBOutlet weak var textField: UITextField! 

override func viewDidLoad() 
{ 
    super.viewDidLoad() 



} 

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

func textFieldShouldBeginEditing(textField: UITextField) -> Bool { 
    let keyboardDoneButtonShow = UIToolbar(frame: CGRectMake(200,200, self.view.frame.size.width,30)) 

    keyboardDoneButtonShow.barStyle = UIBarStyle .BlackTranslucent 
    let button: UIButton = UIButton() 
    button.frame = CGRectMake(0, 0, 65, 20) 
    button.setTitle("Done", forState: UIControlState .Normal) 
    button.addTarget(self, action: Selector("textFieldShouldReturn:"), forControlEvents: UIControlEvents .TouchUpInside) 
    button.backgroundColor = UIColor .clearColor() 

    let doneButton: UIBarButtonItem = UIBarButtonItem() 
    doneButton.customView = button 
    let negativeSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil) 
    negativeSpace.width = -10.0 
    let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) 

    let toolbarButton = [flexSpace,doneButton,negativeSpace] 
    keyboardDoneButtonShow.setItems(toolbarButton, animated: false) 
    textField.inputAccessoryView = keyboardDoneButtonShow 
    return true 
} 

func textFieldShouldReturn(textField: UITextField) -> Bool { 
    self.view.endEditing(true) 
    return false 
} 
} 

Here is my result-

回答

0

我想你沒有你的文本字段的委託設置爲您的視圖控制器。在viewDidLoad中加入以下內容:

self.textField.delegate = self 
+0

謝謝!我不知道我是怎麼忘記的:) – Aleksandr

相關問題