我想创建一个UDatePicker以允许用户进行预约。 UIDatePicker应该在当天提前7天显示,并且在预约完成后,将弹出一个通知,表明它已被确认。
用户界面无关紧要,基本没什么问题。那可能吗?我一直在网上搜索,但找不到任何有用的东西。
任何帮助都将不胜感激。
答案 0 :(得分:0)
class ViewController: UIViewController , UIPickerViewDelegate,
UIPickerViewDataSource
{
var pickerView: UIPickerView!
@IBOutlet weak var textField: UITextField!
var arrDate = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
arrDate.append(Date().getDateStringWithFormate("yyyy-MM-dd", timezone: TimeZone.current.abbreviation()!))
for i in 1...7
{
let dateAdded = Date().addDays(i)
arrDate.append(dateAdded.getDateStringWithFormate("yyyy-MM-dd", timezone: TimeZone.current.abbreviation()!))
print(arrDate)
}
pickerView = UIPickerView()
pickerView.delegate = self
pickerView.dataSource = self
let keyboardToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 44))
keyboardToolbar.barStyle = .black
keyboardToolbar.tintColor = UIColor.white
let barButtonItem = UIBarButtonItem(title: NSLocalizedString("Done", comment: ""), style: .done, target: self, action: #selector(clickToKeyboardToolbarDone(sender:)))
//(barButtonSystemItem: .done, target: self, action: #selector(clickToKeyboardToolbarDone(sender:)))
let flex = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
let items = [flex, barButtonItem]
keyboardToolbar.setItems(items, animated: true)
textField.inputAccessoryView = keyboardToolbar
textField.inputView = pickerView
}
@IBAction func clickToKeyboardToolbarDone(sender: UIBarButtonItem)
{
if(textField.isFirstResponder)
{
let selectedIndex = pickerView.selectedRow(inComponent: 0)
let currentDate = arrDate[selectedIndex]
print("currentDate",currentDate)
}
textField.resignFirstResponder()
}
//MARK: - UIPickerViewDelegate, UIPickerViewDataSource Methods
func numberOfComponents(in pickerView: UIPickerView) -> Int
{
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
{
return arrDate.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
{
return arrDate[row]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
//MARK: - All Date Extension
extension Date
{
func getDateStringWithFormate(_ formate: String, timezone: String) -> String
{
let formatter = DateFormatter()
formatter.dateFormat = formate
formatter.timeZone = TimeZone(abbreviation: timezone)
return formatter.string(from: self)
}
}
你可以使用customepicker视图,在今天最多7天制作日期数组,试试这段代码。