Xamarin.iOS点击UITextView不弹出键盘问题求助
问题解决:Xamarin中UITextView光标闪烁但键盘不弹出
问题原因分析
- 多窗口冲突:AppDelegate和SceneDelegate同时创建了独立的UIWindow实例,导致系统无法识别正确的活跃窗口,键盘无法绑定到有效窗口。
- SceneDelegate依赖已删除的Storyboard:你已删除main.storyboard,但SceneDelegate仍尝试通过
storyboard.InstantiateViewController实例化控制器,既存在潜在空引用风险,也与AppDelegate的代码创建逻辑冲突。 - FirstViewController构造函数不匹配:代码创建控制器需要无参构造函数,但你仅实现了用于Storyboard实例化的
IntPtr构造,导致实例化逻辑存在隐患。 - 多余的FirstResponder调用:在
Started事件中手动调用BecomeFirstResponder属于重复操作,可能干扰系统的键盘唤起流程。
解决方案
1. 统一窗口管理(清理AppDelegate冗余代码)
iOS 13+ 由SceneDelegate负责窗口生命周期,删除AppDelegate中FinishedLaunching内的窗口与控制器创建代码,仅保留全局初始化逻辑:
public bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) { // 仅保留必要的全局初始化,移除所有window、控制器创建代码 return true; }
2. 修正SceneDelegate,纯代码创建控制器
既然已删除main.storyboard,SceneDelegate直接通过代码构建界面:
public void WillConnect(UIScene scene, UISceneSession session, UISceneConnectionOptions connectionOptions) { var windowScene = scene as UIWindowScene; Window = new UIWindow(windowScene); // 代码创建标签栏控制器 var tabBar = new UITabBarController(); // 代码创建FirstViewController var firstViewController = new FirstViewController(); firstViewController.lb.Text = "BYE"; tabBar.ViewControllers = new UIViewController[] { firstViewController }; Window.RootViewController = tabBar; Window.MakeKeyAndVisible(); }
3. 完善FirstViewController构造与控件逻辑
添加无参构造适配代码创建场景,移除多余的FirstResponder调用:
public partial class FirstViewController : UIViewController { public UILabel lb; public UITextView tb; // 无参构造,用于代码创建控制器 public FirstViewController() : base() { InitializeControls(); } // Storyboard实例化专用构造(保留以兼容潜在场景) public FirstViewController(IntPtr handle) : base(handle) { InitializeControls(); } // 提取控件初始化逻辑,避免代码重复 private void InitializeControls() { lb = new UILabel(); lb.Frame = new CoreGraphics.CGRect(100, 100, 100, 40); lb.TextColor = UIColor.Black; lb.Text = "HELLO"; tb = new UITextView(new CoreGraphics.CGRect(200, 200, 100, 40)); tb.BackgroundColor = UIColor.Black; tb.TextColor = UIColor.White; // 建议添加,避免黑色背景看不到文字 tb.Editable = true; // 显式确认可编辑(默认值为true,若被修改可恢复) } public override void ViewDidLoad() { base.ViewDidLoad(); View.AddSubviews(lb, tb); } public override void DidReceiveMemoryWarning() { base.DidReceiveMemoryWarning(); } }
4. 额外检查项
- 清理Info.plist中残留的
UISceneConfiguration与Storyboard关联配置 - 清理项目缓存,重启模拟器/真机后重新运行
内容的提问来源于stack exchange,提问作者Salim KHabitov
相关产品推荐
相关产品推荐

