iOS 如何通过键盘显示 UIView

How to display UIView over keyboard in iOS

我想在用户点击 inputAccessoryView 中的 "Attach" 按钮时通过键盘创建一个简单的视图。 像这样:

有简单的方法吗?或者我应该创建自定义键盘?

您可以将新的子视图添加到您的应用程序中 window。

func attach(sender : UIButton)
{
    // Calculate and replace the frame according to your keyboard frame
    var customView = UIView(frame: CGRect(x: 0, y: self.view.frame.size.height-300, width: self.view.frame.size.width, height: 300))
    customView.backgroundColor = UIColor.redColor()
    customView.layer.zPosition = CGFloat(MAXFLOAT)
    var windowCount = UIApplication.sharedApplication().windows.count
    UIApplication.sharedApplication().windows[windowCount-1].addSubview(customView);
}

你有没有找到一些有效的方法来解决这个问题?在 iOS9 中,您将自定义视图放在 windows:

的顶部
UIApplication.sharedApplication().windows[windowCount-1].addSubview(customView);

但如果键盘关闭,顶部的 Windows 将被删除,因此您的 customView 将被删除。 期待您的帮助! 感谢您的帮助!

虽然这可以通过访问最上面的 window 实现,但我会 避免 这样做,因为它显然会干扰 Apple 的指导方针。

我会做的是关闭键盘并用相同尺寸的视图替换它的框架。

可以从 here 列出的键盘通知访问键盘框架,它们 userInfo 包含一个可以使用 UIKeyboardFrameEndUserInfoKey.

访问的键

Swift 4.0

let customView = UIView(frame: CGRect(x: 0, y: self.view.frame.size.height-300, width: self.view.frame.size.width, height: 300))
customView.backgroundColor = UIColor.red
customView.layer.zPosition = CGFloat(MAXFLOAT)
let windowCount = UIApplication.shared.windows.count
UIApplication.shared.windows[windowCount-1].addSubview(customView)

Swift 4版本:

let customView = UIView(frame: CGRect(x: 0, y: self.view.frame.size.height - 300, width: self.view.frame.size.width, height: 300))
customView.backgroundColor = UIColor.red
customView.layer.zPosition = CGFloat(Float.greatestFiniteMagnitude)
UIApplication.shared.windows.last?.addSubview(customView)

诀窍是将 customView 作为顶部子视图添加到容纳键盘的 UIWindow - 它恰好是 UIApplication.shared.windows 中的最后一个 window .

您绝对可以将视图添加到应用程序的 window,也可以完全添加另一个 window。您可以设置其框架和级别。级别可以是 UIWindowLevelAlert

正如 Tamás Sengel 所说,Apple 的指南不支持通过键盘添加视图。在 Swift 4 & 5 中通过键盘添加视图的推荐方法是:

1) 在故事板中使用 "Next" 按钮添加视图作为外部视图,并在 class 中连接(参见解释图像),在我的例子中:

IBOutlet private weak var toolBar: UIView!

2) 对于要通过键盘添加自定义视图的文本字段,将其添加为 viewDidLoad 中的附件视图:

override func viewDidLoad() {
    super.viewDidLoad()
    phoneNumberTextField.inputAccessoryView = toolBar
}

3) 为 "Next" 按钮添加操作:

@IBAction func nextButtonPressed(_ sender: Any) {
    descriptionTextView.becomeFirstResponder()

    // or -> phoneNumberTextField.resignFirstResponder()
}

解释图像

方法二:图片结果

在 TableView 控制器中 - 在底部添加 stricked 视图

如果您想使用此方法(2),请按照这个很棒的link 处理iPhone X 等屏幕的安全区域。文章:InputAccessoryView and iPhone X

override var inputAccessoryView: UIView? {
    return toolBar
}

override var canBecomeFirstResponder: Bool {
    return true
}