swift - Change Current Date To One Before / One After - Swift DatePicker
问题描述
I have a date picker. I would like to change the date displayed to a date before or after using gesture control. Ie, when a person swipes left the date goes one day behind and if a person swipes right the date goes one day after. I am not sure how to implement this as I have tried the method below but i get an error stating 'Cannot convert value of type 'UITextField?' to expected argument type'Date'. If someone could help me out or point me in the right direction I would appreciate that a lot! Thanks
View Controller:
@IBOutlet weak var userDate: UITextField!
private var datePicker: UIDatePicker?
override func viewDidLoad() {
super.viewDidLoad()
datePicker = UIDatePicker()
datePicker?.datePickerMode = .date
datePicker?.addTarget(self, action: #selector(Test.dateChanged(datePicker:)), for: .valueChanged)
userDate.inputView = datePicker
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE, MMM d, yyyy"
let todayDate = dateFormatter.string(from: Date.init())
self.userDate.text = todayDate
let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(self.handleGesture(gesture:)))
swipeLeft.direction = .left
self.view.addGestureRecognizer(swipeLeft)
let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(self.handleGesture(gesture:)))
swipeRight.direction = .right
self.view.addGestureRecognizer(swipeRight)
}
@objc func handleGesture(gesture: UISwipeGestureRecognizer) -> Void {
if gesture.direction == UISwipeGestureRecognizer.Direction.right {
print("Swipe Right")
view.backgroundColor = .black
// WHERE I WOULD LIKE TO CHANGE THE DATE ONE DAY AFTER
}
else if gesture.direction == UISwipeGestureRecognizer.Direction.left {
print("Swipe Left")
view.backgroundColor = .yellow
// WHERE I WOULD LIKE TO CHANGE THE DATE ONE DAY BEFORE
}
}
I tried this method but this is where I get the error:
Calendar.current.date(byAdding: .day, value: 1, to: userDate)!
解决方案
The function date(byAdding:value:to:options:)
expects a date type to be passed as a parameter. You are passing UITextField instead of a date type.
I think what you want to do is
Calendar.current.date(byAdding: .day, value: 1, to: datePicker.date)!
推荐阅读
- postgresql - 将qgis上不同多边形层上的每个点元素分开
- graphql - 如何塑造我的 graphql 后端响应?
- python - Tensorflow 只能看到 XLA_GPUs 而不能使用它们
- firebase - Firebase + Flutter:获取用于登录的平台用户
- sql - sql中的自定义排序
- java - 如何解析 XML 标签外的文本?
- c++ - 将头文件包含到命名空间时,为什么 Intellisense 无法从头文件中找到变量?
- jquery - 如何显示特定于下拉选择的隐藏 div?
- excel - 如果列包含日期,则 IF 语句计算日期之间的天数
- node.js - 为 npm run 创建别名