文章目录 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)}}