消息机制iOS-SwiftSwiftUI教程与源码

SwiftUI封装UIKit之UIDatePicker

2020-06-10  本文已影响0人  iCloudEnd

本文价值与收获

看完本文后,您将能够作出下面的界面

Jietu20200610-095142@2x.jpg

看完本文您将掌握的技能

代码

import SwiftUI

struct ContentView: View {
    @State var date = Date()
    var body: some View {
        VStack{
            Text("SwiftUI封装UIKit之UIPicker")
        UDatePicker(date: self.$date)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}


struct UDatePicker: UIViewRepresentable {
    @Binding var date: Date

    private let datePicker = UIDatePicker()

    func makeUIView(context: Context) -> UIDatePicker {
        datePicker.datePickerMode = .date
        //datePicker.datePickerStyle = .m
        datePicker.addTarget(context.coordinator, action: #selector(Coordinator.changed(_:)), for: .valueChanged)
        return datePicker
    }

    func updateUIView(_ uiView: UIDatePicker, context: Context) {
        datePicker.date = date
    }

    func makeCoordinator() -> UDatePicker.Coordinator {
        Coordinator(date: $date)
    }

    class Coordinator: NSObject {
        private let date: Binding<Date>

        init(date: Binding<Date>) {
            self.date = date
        }

        @objc func changed(_ sender: UIDatePicker) {
            self.date.wrappedValue = sender.date
        }
    }
}

推荐

基础文章推荐

经典教程推荐

技术源码推荐

推荐文章

CoreData篇

Combine篇

TextField篇

JSON文件篇


一篇文章系列

技术交流

QQ:3365059189
SwiftUI技术交流QQ群:518696470

上一篇下一篇

猜你喜欢

热点阅读