iOS / SwiftUI 输入法(键盘)布局处理总结(AI版)
文章目录 iOS / SwiftUI 输入法键盘处理总结一、问题背景二、输入框切换闪烁问题❌ 错误原因解决办法键盘动画类似 Android InsetsuikitswiftUI iOS / SwiftUI 输入法键盘处理总结一、问题背景在 iOS / SwiftUI 开发中常见输入法问题输入框切换时键盘闪烁键盘弹出/收起动画不自然无法像 Android WindowInsetsAnimation 一样平滑跟随二、输入框切换闪烁问题❌ 错误原因focusedFieldnilfocusedField.password解决办法enumField{caseusernamecasepassword}FocusStateprivatevarfocusedField:Field?TextField(用户名,text:$username).focused($focusedField,equals:.username)SecureField(密码,text:$password).focused($focusedField,equals:.password)❗ 注意不要先设为 nil不要手动关闭键盘使用系统焦点切换键盘动画类似 Android InsetsuikitobjcfunckeyboardWillChangeFrame(_notification:Notification){guardletuserInfonotification.userInfoelse{return}letdurationuserInfo[UIResponder.keyboardAnimationDurationUserInfoKey]as?Double??0.25letcurveRawuserInfo[UIResponder.keyboardAnimationCurveUserInfoKey]as?UInt??0letcurveUIView.AnimationOptions(rawValue:curveRaw16)letframeuserInfo[UIResponder.keyboardFrameEndUserInfoKey]as?CGRect??.zeroletkeyboardHeightUIScreen.main.bounds.height-frame.origin.yUIView.animate(withDuration:duration,delay:0,options:curve){self.bottomConstraint.constantkeyboardHeightself.view.layoutIfNeeded()}}swiftUI推荐.safeAreaInset(edge:.bottom){Color.clear.frame(height:0)}combineclassKeyboardObserver:ObservableObject{Publishedvarheight:CGFloat0privatevarcancellablesSetAnyCancellable()init(){NotificationCenter.default.publisher(for:UIResponder.keyboardWillChangeFrameNotification).map{notification-CGFloatinletframenotification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey]as?CGRect??.zeroreturnUIScreen.main.bounds.height-frame.origin.y}.assign(to:\.height,on:self).store(in:cancellables)}}structContentView:View{StateObjectvarkeyboardKeyboardObserver()varbody:someView{VStack{Spacer()TextField(输入,text:.constant()).textFieldStyle(.roundedBorder)}.padding(.bottom,keyboard.height).animation(.easeOut(duration:0.25),value:keyboard.height)}}
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2494072.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!