【问题标题】:How to make UIViewRepresentable inherit UIView?如何让 UIViewRepresentable 继承 UIView?
【发布时间】: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


【解决方案1】:

每当我们想在 SwiftUI 上下文中使用此视图时,我们通常会将 UIKit 视图 (UIView) 包装为 UIViewRepresentable。 SwiftUI 使用名为 View 的视图元素。

在您的情况下,UIKit 视图是 FSCalendar,它最初是一个 UIView 并将其包装为 UIViewRepresentable 有助于我们在 SwiftUI 上下文中将其用作 SwiftUI 视图 - 因此没有理由将 UIViewRepresentable 转换或制作为 UIView。

【讨论】:

    猜你喜欢
    • 2018-07-30
    • 2015-03-06
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    相关资源
    最近更新 更多