2016-03-31 2 views
3

В моем коде:Swift: Нажмите на текстовое поле, чтобы начать действие

@IBOutlet weak var textField: UITextField! 

@IBAction func textField(sender: AnyObject) { 

    if textField.text != "" { 
     let newSweet = CKRecord(recordType: "Chat") 
     newSweet["content"] = textField.text 
     textField.delegate = self 
     let publicData = CKContainer.defaultContainer().publicCloudDatabase 
     publicData.saveRecord(newSweet, completionHandler: { (record:CKRecord?, error:NSError?) -> Void in 
      if error == nil { 
       dispatch_async(dispatch_get_main_queue(), {() -> Void in 
        self.tableView.beginUpdates() 
        self.sweets.insert(newSweet, atIndex: 0) 
        let indexPath = NSIndexPath(forRow: 0, inSection: 0) 
        self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: 
         .Top) 
        func textFieldShouldReturn(textField: UITextField) -> Bool { 
         self.textField.resignFirstResponder() 

         return true 
        }}) 

      }else{ 
       print(error) 
       } 
     }) 
    } 
} 

Я пытаюсь получить доступ к cloudKit поэтому, когда вы печатаете что-то в UITextField Активизирует UITextField@IBAction. Что происходит, когда я ввожу текст в UITextField, ничего не происходит, поэтому мне нужно активировать @IBAction. у кого-нибудь есть решение?

+0

Вы должны использовать функцию TextFieldDelegate, чтобы сделать это – Khuong

ответ

3

Используйте методы этого делегата

class ViewController: UIViewController,UITextFieldDelegate //set delegate to class 

@IBOutlet var txtValue: UITextField    //create a textfile variable 

override func viewDidLoad() { 
    super.viewDidLoad() 
    txtValue.delegate = self     //set delegate to textfile 
} 


func textFieldDidBeginEditing(textField: UITextField!) { //delegate method 

let newSweet = CKRecord(recordType: "Chat") 
     newSweet["content"] = textField.text 
     textField.delegate = self 
     let publicData = CKContainer.defaultContainer().publicCloudDatabase 
     publicData.saveRecord(newSweet, completionHandler: { (record:CKRecord?, error:NSError?) -> Void in 
      if error == nil { 
       dispatch_async(dispatch_get_main_queue(), {() -> Void in 
        self.tableView.beginUpdates() 
        self.sweets.insert(newSweet, atIndex: 0) 
        let indexPath = NSIndexPath(forRow: 0, inSection: 0) 
        self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: 
         .Top) 
       func textFieldShouldReturn(textField: UITextField) -> Bool { 
        self.textField.resignFirstResponder() 

        return true 
} 

func textFieldShouldEndEditing(textField: UITextField!) -> Bool { //delegate method 
    return false 
} 

func textFieldShouldReturn(textField: UITextField!) -> Bool { //delegate method 
    textField.resignFirstResponder() 

    return true 
} 
+0

Пыталось у моего ответ? –

+0

Это не работает. Я сделал именно то, что вы сделали, но когда я нажимаю кнопку, ничего не происходит. –

+0

По какой-то причине это не работает. –

4

В вашем ViewController, протокол импорта UITextFieldDelegate так:

class YourViewController: UIViewController,UITextFieldDelegate 

в вашем viewDidLoad сделать так:

override func viewDidLoad() { 
    super.viewDidLoad() 
    textField.delegate = self 
} 

И вы должны установить делегат метод:

func textFieldDidBeginEditing(textField: UITextField!) { 
     let newSweet = CKRecord(recordType: "Chat") 
     newSweet["content"] = textField.text 
     textField.delegate = self 
     let publicData = CKContainer.defaultContainer().publicCloudDatabase 
     publicData.saveRecord(newSweet, completionHandler: { (record:CKRecord?, error:NSError?) -> Void in 
      if error == nil { 
       dispatch_async(dispatch_get_main_queue(), {() -> Void in 
        self.tableView.beginUpdates() 
        self.sweets.insert(newSweet, atIndex: 0) 
        let indexPath = NSIndexPath(forRow: 0, inSection: 0) 
        self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: 
         .Top) 
        func textFieldShouldReturn(textField: UITextField) -> Bool { 
         self.textField.resignFirstResponder() 

         return true 
        }}) 

} 

Если вы хотите нажать Return на Keyboard уволят клавиатуры, вы должны установить эту TextFieldDelegate методы

func textFieldShouldReturn(textField: UITextField) -> Bool { 
     self.textField.resignFirstResponder() 
     return true 
    } 
+0

Когда я нажимаю кнопку ввода, он все равно не работает. –

+0

Я заменил другой @IBAction на func textFieldDidBeginEditing –

+0

не работает, вы знаете, как его исправить? Благодаря! –

Смежные вопросы