【发布时间】:2015-12-19 03:48:18
【问题描述】:
【问题讨论】:
标签: ios swift uiview uikeyboard
【问题讨论】:
标签: ios swift uiview uikeyboard
正如 Tamás Sengel 所说,Apple 的指南不支持在键盘上添加视图。在 Swift 4 和 5 中添加键盘视图的推荐方法是:
1) 在故事板中添加带有“下一步”按钮的视图作为外部视图并在您的班级中连接(请参阅解释图像),在我的情况下:
IBOutlet private weak var toolBar: UIView!
2) 对于要在键盘上添加自定义视图的文本字段,将其添加为 viewDidLoad 中的附件视图:
override func viewDidLoad() {
super.viewDidLoad()
phoneNumberTextField.inputAccessoryView = toolBar
}
3) 为“下一步”按钮添加操作:
@IBAction func nextButtonPressed(_ sender: Any) {
descriptionTextView.becomeFirstResponder()
// or -> phoneNumberTextField.resignFirstResponder()
}
方法二:带图结果
在 TableView 控制器中 - 在底部添加删除视图
如果您想使用此方法 (2),请点击此链接来处理 iPhone X 等屏幕的安全区域。文章:InputAccessoryView and iPhone X
override var inputAccessoryView: UIView? {
return toolBar
}
override var canBecomeFirstResponder: Bool {
return true
}
【讨论】:
你有没有找到一些有效的方法来解决这个问题?在 iOS9 中,您将 customView 放在窗口的顶部:
UIApplication.sharedApplication().windows[windowCount-1].addSubview(customView);
但如果键盘关闭,顶部的 Windows 将被删除,因此您的 customView 将被删除。
期待您的帮助!
感谢您的帮助!
【讨论】:
您绝对可以将视图添加到应用程序的窗口中,也可以完全添加另一个窗口。您可以设置它的框架和水平。级别可以是UIWindowLevelAlert。
【讨论】:
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 中的最后一个窗口。
【讨论】:
windows 而不是 keyWindow 的最后一个工作!
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)
【讨论】:
虽然这可以通过访问最顶部的窗口来实现,但我会避免这样做,因为它明显违反了 Apple 的准则。
我要做的是关闭键盘并用相同尺寸的视图替换它的框架。
键盘的框架可以通过here 列出的键盘通知访问,它们的userInfo 包含一个可以通过UIKeyboardFrameEndUserInfoKey 访问的键。
【讨论】:
您可以将该新子视图添加到您的应用程序窗口。
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);
}
【讨论】:
sender.window代替UIApplication.sharedApplication().windows[...]吗?