例如如何从FSCalendar获取selectedDate?
struct CalendarController: UIViewControllerRepresentable {
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIViewController(context: UIViewControllerRepresentableContext<CalendarController>)
-> calendars {
let calendarViewController = calendars()
return calendarViewController
}
func updateUIViewController(_ uiViewController: calendars, context:
UIViewControllerRepresentableContext<CalendarController>) {
}
func updateUIViewController(_ uiViewController: CalendarController, context:
UIViewControllerRepresentableContext<CalendarController>) {
}
class Coordinator: NSObject {
var parent: CalendarController
init(_ calendarViewController: CalendarController) {
self.parent = calendarViewController
}
}
}
class calendars: UIViewController, FSCalendarDelegate, ObservableObject {
var calendar = FSCalendar()
@Published var selectedData : Date?
override func viewDidLoad() {
super.viewDidLoad()
calendar.delegate = self
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
calendar.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height:
view.frame.size.width)
view.addSubview(calendar)
}
func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition:
FSCalendarMonthPosition) {
print("didSelect date: \(date)")
selectedData = date
}
}
struct CalendarView: View {
var body: some View{
CalendarController().padding().frame(alignment: .top)
}
}
struct Calendar_Previews: PreviewProvider {
static var previews: some View {
CalendarView()
}
}
稍后在另一个快速视图中,我尝试获取日期,但它从未更改。 我用
@ObservedObject var calendarData = calendars()
//...
CalendarView().scaledToFit()
Text("\(self.calendarData.selectedData ?? Date())")
答案 0 :(得分:0)
以下作品。
由于我是iOS的新用户,所以我很快就找不到代理的诀窍。
协调器类应实现它以使其正常工作。
''' 导入SwiftUI 导入UIKit 进口FSCalendar 导入合并
struct CalendarController:UIViewControllerRepresentable {
@Binding var selectedDate : Date?
func makeCoordinator() -> CalendarController.Coordinator {
Coordinator(self)
}
func makeUIViewController(context: Context) -> calendars {
let calendar = calendars()
calendar.calendar.delegate = context.coordinator
return calendar
}
func updateUIViewController(_ uiViewController: calendars, context: Context) {
}
}
class calendars: UIViewController {
var calendar = FSCalendar()
var selectedDate : Date?
override func viewDidLoad() {
super.viewDidLoad()
calendar.delegate = self // delegate
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
calendar.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height:
view.frame.size.width)
view.addSubview(calendar)
}
}
extension CalendarController {
class Coordinator: NSObject, FSCalendarDelegate {
var parent: CalendarController
init(_ parent: CalendarController) {
self.parent = parent
}
func calendar(_ calendar: FSCalendar, didSelect date: Date, at
monthPosition: FSCalendarMonthPosition) {
print(date)
parent.selectedDate = date
}
}
}
'''