UIKit嵌套SwiftUI登錄頁面實練

在UIkit框架中嵌套部分swiftUI之UIViewController中添加SwiftUI視圖
系統(tǒng)適配最低版本:iOS13

將swiftUI視圖添加至UIViewController中

1.需要使用UIHostingController
2.計算出swiftUI視圖的尺寸
3.如果有導航欄隱藏,注意處理
代碼:

  @discardableResult
    func addSwiftUIView<Content: View>(_ rhs: Content) -> UIHostingController<Content> {
        let vc = UIHostingController(rootView: rhs)
        vc.view.backgroundColor = .clear
        vc.edgesForExtendedLayout = []
        self.addChild(vc)
        
        self.view.addSubview(vc.view)
       
//        vc.view.sizeToFit()
        
        printLog("之前計算出來的size = \(vc.view.frame.size)")
        /// 使用該方法 計算swiftUI部分的高度碍岔,便于在UIKit中進行布局
        let targetSize = CGSize(width: view.bounds.width, height: UIView.layoutFittingCompressedSize.height)
        let size = vc.sizeThatFits(in: targetSize)
        printLog("計算出來的size = \(size)")
        vc.view.frame.size = size
        
        vc.view.translatesAutoresizingMaskIntoConstraints = false
        self.navigationController?.setNavigationBarHidden(true, animated: false)
  
        vc.didMove(toParent: self)
        return vc
    }

登錄頁面其他登錄方式部分的SwiftUI實現(xiàn)代碼

1.同樣需要注意如果導航欄隱藏需要進行處理
2.iOS13上浴讯,給Button設置圖片時,注意渲染模式

struct AppLoginWayView: View {
    var wayAction: (AppLogiWayType) -> Void
    
    var ways: [AppLogiWayType] = [.password, .qq, .mobile]
    
    var body: some View {
        
        HStack(spacing: 30.baobao.less, content: {
            ForEach(ways) { way in
                Button {
                    wayAction(way)
                } label: {
                    VStack(spacing: 4, content: {
                        Image(way.image_name)
                            .resizable()
                            .renderingMode(.original)
                            .scaledToFit()
                            .frame(width: 46.baobao.less, height: 46.baobao.less, alignment: .center)
                        
                        Text(way.title)
                            .font(.custom(AppFontName.regular.rawValue, size: 12.baobao.less))
                            .foregroundColor(Color("text_main", bundle: nil))
                    }).padding(0)
                }
                .background(Color.clear)
                

            }
        })
        .padding(0)
        .edgesIgnoringSafeArea(.all)
        .navigationBarHidden(true)
        .onAppear(perform: {
            if let nav = UIApplication.shared.baobao.getCurrentVC()?.navigationController {
                 nav.isNavigationBarHidden = true
                 nav.navigationItem.hidesBackButton = true
                 nav.navigationBar.isHidden = true
             }
            
        })
    }
}

UIViewController與SwiftUI的狀態(tài)記錄與交互問題

1.ObservableObject 管理狀態(tài)
2.Toggle使用
3.自定義ToggleStyle

class AgreementState: ObservableObject {
    @Published var isAgreed: Bool

    init(isAgreed: Bool) {
        self.isAgreed = isAgreed
    }
}

// ObservableObject 管理狀態(tài)
    private var agreementState = AgreementState(isAgreed: App.Config.shared.is_agree_login_protocol)


    private lazy var agreementView = LoginAgreementView(state: agreementState, clickAction: {[weak self] agreement in
        self?.didAgreementClicked(agreement)
    }, onToggle: { [weak self] isOn in
        guard let self = self else { return }

        self.agreementState.isAgreed = isOn
        App.Config.shared.is_agree_login_protocol = isOn
        baobaoLog(".isAgree = \(self.agreementState.isAgreed), app.agree = \(App.Config.shared.is_agree_login_protocol)")

    })
struct LoginAgreementView: View {
    @ObservedObject var state: AgreementState
//    @Binding var isAgreed: Bool
    var protocls: [ProtocolModel] = [ProtocolConfig.shared.user, ProtocolConfig.shared.privacy]
    var clickAction: (ProtocolModel) -> Void

    var onToggle: (Bool) -> Void

    var body: some View {
        HStack(spacing: 8.less, content: {

            Toggle(isOn: $state.isAgreed, label: {
                HStack(spacing: 0, content: {
                    Text("我已閱讀并同意")
                        .font(.custom(getFontName(style: .regular), size: 12.less))
                        .foregroundColor(Color("text"))
                    ForEach(protocls, id: \.url) { agreement in
                        AgreementTextView(text: agreement.title, action: {
                            clickAction(agreement)
                        })
                    }

                })
            })
            .toggleStyle(CheckBoxToggleStyle(onToggle: onToggle))

        })
        .padding(0)
        .fixedSize()
        .edgesIgnoringSafeArea(.all)
        .navigationBarHidden(true)
        .onAppear(perform: {
            if let nav = UIApplication.topViewController()?.navigationController {
                nav.isNavigationBarHidden = true
                nav.setNavigationBarHidden(true, animated: false)
            }
        })
    }
}




//#Preview {
//    LoginAgreementView()
//}


struct AgreementTextView: View {
    let text: String
    let action: () -> Void

    var body: some View {
        Text(text)
            .foregroundColor(Color("agreement"))
            .font(.custom(getFontName(style: .regular), size: 12.less))
            .onTapGesture {
                action()
            }
    }
}


struct CheckBoxToggleStyle: ToggleStyle {
    let onToggle: (Bool) -> Void

    func makeBody(configuration: Configuration) -> some View {
        Button(action: {
            configuration.isOn.toggle()
            print("是否綁定 \(configuration.isOn)")
            onToggle(configuration.isOn)
        }) {
            HStack {
                Image(configuration.isOn ? .selectedBlack : .selectUnIcon)
                    .renderingMode(.original)
                configuration.label
            }
        }
        .buttonStyle(.plain)
        .padding(0)
        .background(Color.clear)

    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末蔼啦,一起剝皮案震驚了整個濱河市兰珍,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖掠河,帶你破解...
    沈念sama閱讀 218,284評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件亮元,死亡現(xiàn)場離奇詭異,居然都是意外死亡唠摹,警方通過查閱死者的電腦和手機爆捞,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來勾拉,“玉大人煮甥,你說我怎么就攤上這事∨涸蓿” “怎么了成肘?”我有些...
    開封第一講書人閱讀 164,614評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長斧蜕。 經(jīng)常有香客問我双霍,道長批销,這世上最難降的妖魔是什么洒闸? 我笑而不...
    開封第一講書人閱讀 58,671評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮均芽,結(jié)果婚禮上丘逸,老公的妹妹穿的比我還像新娘。我一直安慰自己掀宋,他們只是感情好深纲,可當我...
    茶點故事閱讀 67,699評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著劲妙,像睡著了一般湃鹊。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上是趴,一...
    開封第一講書人閱讀 51,562評論 1 305
  • 那天涛舍,我揣著相機與錄音,去河邊找鬼唆途。 笑死富雅,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的肛搬。 我是一名探鬼主播没佑,決...
    沈念sama閱讀 40,309評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼温赔!你這毒婦竟也來了蛤奢?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,223評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎啤贩,沒想到半個月后待秃,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,668評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡痹屹,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,859評論 3 336
  • 正文 我和宋清朗相戀三年章郁,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片志衍。...
    茶點故事閱讀 39,981評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡暖庄,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出楼肪,到底是詐尸還是另有隱情培廓,我是刑警寧澤,帶...
    沈念sama閱讀 35,705評論 5 347
  • 正文 年R本政府宣布春叫,位于F島的核電站肩钠,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏象缀。R本人自食惡果不足惜蔬将,卻給世界環(huán)境...
    茶點故事閱讀 41,310評論 3 330
  • 文/蒙蒙 一爷速、第九天 我趴在偏房一處隱蔽的房頂上張望央星。 院中可真熱鬧,春花似錦惫东、人聲如沸莉给。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,904評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽颓遏。三九已至,卻和暖如春滞时,著一層夾襖步出監(jiān)牢的瞬間叁幢,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,023評論 1 270
  • 我被黑心中介騙來泰國打工坪稽, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留曼玩,地道東北人。 一個月前我還...
    沈念sama閱讀 48,146評論 3 370
  • 正文 我出身青樓窒百,卻偏偏與公主長得像黍判,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子篙梢,可洞房花燭夜當晚...
    茶點故事閱讀 44,933評論 2 355

推薦閱讀更多精彩內(nèi)容