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

Swift中取消图片选择器后Input Accessory View消失的解决问询

解决inputAccessoryView关闭相册后消失的问题

这个问题我之前也碰到过,核心原因是:当你present相册选择器UIImagePickerController时,当前页面的textView会失去第一响应者状态,键盘随之收起,而默认情况下inputAccessoryView是和键盘绑定显示的,所以它也会跟着消失。关闭相册后,系统不会自动帮你把textView恢复成第一响应者,所以inputAccessoryView就不会自动回来了。

给你两个关键的修复步骤,结合你的代码来调整:

1. 确保ViewController能成为第一响应者

inputAccessoryView的显示依赖于当前ViewController具备成为第一响应者的能力,你需要在ViewController里添加这个重写:

override var canBecomeFirstResponder: Bool {
    return true
}

2. 关闭相册后手动恢复textView的第一响应者状态

你已经设置了UIImagePickerController的delegate,现在需要实现两个代理方法,在相册关闭的回调里,让textView重新成为第一响应者,这样键盘会重新弹出,inputAccessoryView也会跟着回来:

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    dismiss(animated: true) {
        // 在dismiss的completion里执行,确保相册完全关闭后再恢复
        self.textView.becomeFirstResponder()
    }
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    // 先处理你选中的图片逻辑,比如获取图片
    if let selectedImage = info[.originalImage] as? UIImage {
        // 这里写你的图片处理代码
    }
    
    dismiss(animated: true) {
        // 同样在关闭后恢复textView的第一响应者状态
        self.textView.becomeFirstResponder()
    }
}

另外注意你代码里的小疏漏:inputContainerView的初始化少了个右括号,记得补上:

let inputContainerView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 40))

这样调整后,关闭相册时inputAccessoryView就会重新显示在屏幕底部了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:37:29