文本框使用 UIDatePicker
Posted
技术标签:
【中文标题】文本框使用 UIDatePicker【英文标题】:Text boxes uses UIDatePicker 【发布时间】:2016-07-05 14:36:15 【问题描述】:我正在使用 swift 在 Xcode 中创建一个应用程序,并且我有一个使用 UIDatePicker 的文本框,但是现在我的所有其他文本框都在使用这个日期选择器,而我希望它们只是一个数字键盘。任何帮助深表感谢。我想成为 UIDatePicker 的文本框称为“StartDate”,但我还有其他需要成为数字键盘的文本框。我仍然是 Swift 和 XCode 的初学者,但就像我说的,非常感谢所有帮助。
import UIKit
import EventKit
class ViewController: UIViewController, UITextFieldDelegate
weak var StartDate: UITextField!
func textFieldDidBeginEditing(textField: UITextField)
let datePicker = UIDatePicker()
textField.inputView = datePicker
datePicker.datePickerMode = UIDatePickerMode.Date
datePicker.addTarget(self, action: "datePickerChanged:", forControlEvents: .ValueChanged)
func datePickerChanged(sender: UIDatePicker)
let formatter = NSDateFormatter()
formatter.dateStyle = .LongStyle
StartDate.text = formatter.stringFromDate(sender.date)
func textFieldShouldReturn(textField: UITextField) -> Bool
textField.resignFirstResponder()
return true
// Code to close keyboard that can be used throughout the app
func closeKeyboard()
self.view.endEditing(true)
// Close keyboard on touch anywhere else
override func touchesBegan(touches: NSSet, withEvent event: UIEvent)
closeKeyboard()
override func viewDidLoad()
super.viewDidLoad()
StartDate.delegate = self
override func didReceiveMemoryWarning()
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
【问题讨论】:
【参考方案1】:试试这样的:
func textFieldDidBeginEditing(textField: UITextField)
if textField == StartDate
let datePicker = UIDatePicker()
textField.inputView = datePicker
datePicker.datePickerMode = UIDatePickerMode.Date
datePicker.addTarget(self, action: "datePickerChanged:", forControlEvents: .ValueChanged)
else
//do stuff with the rest of the textFields
【讨论】:
以上是关于文本框使用 UIDatePicker的主要内容,如果未能解决你的问题,请参考以下文章