【发布时间】:2022-11-19 00:59:40
【问题描述】:
我有一个第三方库组件 FSCalendar 的 UIViewRepresentable。但是,我需要它来符合 UIView 类型......有没有办法做到这一点?任何帮助表示赞赏:)
struct CalendarViewRepresentable: UIViewRepresentable {
typealias UIViewType = FSCalendar
var calendar = FSCalendar()
@Binding var selectedDate: Date
var calendarHeight: NSLayoutConstraint?
func updateUIView(_ uiView: FSCalendar, context: Context) { }
func makeUIView(context: Context) -> FSCalendar {
calendar.delegate = context.coordinator
calendar.dataSource = context.coordinator
return calendar
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, FSCalendarDelegate, FSCalendarDataSource {
var parent: CalendarViewRepresentable
init(_ parent: CalendarViewRepresentable) {
self.parent = parent
}
func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
parent.selectedDate = date
}
func calendar(_ calendar: FSCalendar, boundingRectWillChange bounds: CGRect, animated: Bool) {
parent.calendarHeight?.constant = bounds.height
parent.calendar.layoutIfNeeded()
}
}
}
struct HomeView: View {
@State private var selectedDate: Date = Date()
var body: some View {
VStack {
CalendarViewRepresentable(selectedDate: self.$selectedDate)
}
}
}
【问题讨论】:
-
你为什么不直接使用
FSCalendar呢?因为UIViewRepresentable是为了在SwiftUI,中使用UIView如果你需要在UIKit中使用它那么你不需要UIViewRepresentable -
@Andrew 我在 SwiftUI 中使用它...我已将调用它的代码添加到上面的 SwiftUI 视图中。抱歉不清楚
标签: ios swift swiftui uiview uiviewrepresentable