SWIFT代码;无法使用标准方法关闭键盘

时间:2014-10-01 21:08:38

标签: ios swift keyboard iphone-keypad

我一直在研究Swift教程。 在教程中,作者忽略了如何解释模拟器上的键盘。 我尝试了我所知道的标准方法; resignFirstResponder() 但是我不断收到错误;无法将字符串转换为bool。 到目前为止,我还没有找到关于Stack溢出的可行答案。 有任何想法吗? 我已经包含了以下代码。

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {


    @IBOutlet weak var yearTextField: UITextField!

    @IBOutlet weak var dayTextField: UITextField!

    @IBOutlet weak var monthTextField: UITextField!


    @IBOutlet weak var messageLabel: UILabel!



    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        self.yearTextField.delegate = self
        self.dayTextField.delegate = self
        self.monthTextField.delegate = self
    }

      //    Suggested fix not working?

     //  func textFieldShouldReturn(textField: UITextField!) -> Bool {
     //   textField.resignFirstResponder()
     //   return true;
     //  }


    @IBAction func daysButtonPressed(sender: AnyObject) {

        println("Days Button Pressed")

        messageLabel.text = "Button pressed"

        messageLabel.resignFirstResponder()



        var dateComponents = NSDateComponents()
        dateComponents.day = dayTextField.text.toInt()! // 28
        dateComponents.month = monthTextField.text.toInt()! // 3
        dateComponents.year =  yearTextField.text.toInt()! // 1956

        var calendar = NSCalendar(identifier: NSGregorianCalendar)
        var birthDate = calendar.dateFromComponents(dateComponents) //NSDate
        var currentDate = NSDate.date()


        println(birthDate)
        println("Current Date \(currentDate)")


        var durationDateComponets = calendar.components(NSCalendarUnit.CalendarUnitDay,
            fromDate: birthDate!,
            toDate: currentDate,
            options: nil)


        var numberOfDaysAlive = durationDateComponets.day

        //Format with commas

        var numberFormatter = NSNumberFormatter()
        numberFormatter.usesGroupingSeparator = true

        var dayString = numberFormatter.stringFromNumber(numberOfDaysAlive)



        messageLabel.text = "Days alive: \(dayString)"


      //   self.messageLabel.resignFirstResponder()


    }


}

1 个答案:

答案 0 :(得分:1)

键盘已启动,因为您的UITextField之一是第一个响应者。由于您不知道哪一个,请在每个人身上调用resignFirstResponder()

daysButtonPressed()而不是致电:

messageLabel.resignFirstResponder()

您需要致电:

dayTextField.resignFirstResponder()
monthTextField.resignFirstResponder()
yearTextField.resignFirstResponder()