You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xcode14中Swift实现UIView置于键盘前方的方法求助

解决Xcode14.2中UIView无法置于键盘前方的问题

问题原因

Xcode14.2对应的iOS版本中,UIApplication.shared.windows已被废弃,且在Scene架构下,原通过windows.last获取窗口的方式无法保证拿到正确的层级容器,导致添加的视图被键盘覆盖。

解决方案

方案1:获取当前活跃的Key Window(推荐)

替换原代码中获取window的逻辑,改用Scene架构下的正确方式获取活跃窗口,同时确保视图处于最上层:

let customView = UIView(frame: CGRect(x: 100, y: 100, width: 200, height: 200))
customView.backgroundColor = UIColor.clear
customView.layer.zPosition = CGFloat(Float.greatestFiniteMagnitude)

// 获取当前活跃的key window
guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
      let window = windowScene.windows.first(where: { $0.isKeyWindow }) else { return }

window.addSubview(customView)
// 强制将视图置于窗口所有子视图最前方
window.bringSubviewToFront(customView)

方案2:直接添加到键盘所在窗口(更可靠)

通过监听键盘弹出通知,找到键盘所在的专属窗口,将视图添加到该窗口上:

// 注册键盘弹出通知(建议在viewDidLoad中执行)
NotificationCenter.default.addObserver(forName: UIResponder.keyboardDidShowNotification, object: nil, queue: .main) { [weak self] _ in
    guard let self = self else { return }
    
    // 定位键盘专属窗口
    guard let keyboardWindow = UIApplication.shared.windows.first(where: { 
        NSStringFromClass($0.classForCoder) == "UIRemoteKeyboardWindow" 
    }) else { return }
    
    let customView = UIView(frame: CGRect(x: 100, y: 100, width: 200, height: 200))
    customView.backgroundColor = .clear
    keyboardWindow.addSubview(customView)
    keyboardWindow.bringSubviewToFront(customView)
    
    // 注意:键盘消失时需移除customView,避免内存泄漏
    NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: .main) { _ in
        customView.removeFromSuperview()
    }
}

注意事项

  • 避免使用UIApplication.shared.windows,iOS13+的Scene架构下该API行为不稳定且已被标记为废弃。
  • 同时使用layer.zPosition和bringSubviewToFront能更稳妥地保证视图层级优先级。

内容的提问来源于stack exchange,提问作者Coder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 21:22:36