如何在iOS中通过键盘显示UIView
当用户点击inputAccessoryView中的“附加”按钮时,我想在键盘上创建一个简单的视图。 大概是这样的:如何在iOS中通过键盘显示UIView,ios,swift,uiview,uikeyboard,Ios,Swift,Uiview,Uikeyboard,当用户点击inputAccessoryView中的“附加”按钮时,我想在键盘上创建一个简单的视图。 大概是这样的: 有没有简单的方法?或者我应该创建自定义键盘?您可以将新的子视图添加到应用程序窗口中 func attach(sender : UIButton) { // Calculate and replace the frame according to your keyboard frame var customView = UIView(frame: CGRect(x:
有没有简单的方法?或者我应该创建自定义键盘?您可以将新的子视图添加到应用程序窗口中
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中,您将customView放在窗口顶部:
UIApplication.sharedApplication().windows[windowCount-1].addSubview(customView);
但是如果键盘关闭,顶部窗口将被删除,因此您的customView
将被删除。
期待您的帮助!
谢谢你的帮助 虽然这可以通过访问最上面的窗口来实现,但我会避免这样做,因为这显然会干扰苹果的指导方针 我要做的是放弃键盘,用相同尺寸的视图替换它的框架
可以从列出的键盘通知访问键盘框架,它们的
userInfo
包含一个键,可以使用UIKeyboardFrameEndUserInfoKey
访问该键
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
中的最后一个窗口。您完全可以将视图添加到应用程序的窗口中,也可以完全添加另一个窗口。可以设置其框架和标高。级别可以是UIWindowLevelAlert
正如Tamás Sengel所说,苹果的指南不支持在键盘上添加视图。在Swift 4和5中,建议在键盘上添加视图的方法是:
1) 在故事板中添加带有“下一步”按钮的视图作为外部视图,并在类中连接(请参见解释图),在我的示例中:
IBOutlet private weak var toolBar: UIView!
2) 对于要在键盘上添加自定义视图的文本字段,请将其作为附件视图添加到viewDidLoad中:
override func viewDidLoad() {
super.viewDidLoad()
phoneNumberTextField.inputAccessoryView = toolBar
}
3) 为“下一步”按钮添加操作:
解释图像:
方法2:图像结果
在TableView控制器中-在底部添加带条纹的视图
如果您想使用此方法,请按照此链接处理iPhone X等屏幕的安全区域(2)。第条:
您可以使用
sender.window
而不是UIApplication.sharedApplication().windows[…]
?@rintaro:这样做行不通,会在键盘下方添加视图。这是一个有问题的解决方案,应该避免。窗口层次结构可以在任何新引入的iOS版本上更改。请查看我的答案,我这样解决这个问题-这应该是正确的答案。谢谢用户doca。你就是那个人。从UIApplication获得最后一个windows
,而不是keyWindow
!
@IBAction func nextButtonPressed(_ sender: Any) {
descriptionTextView.becomeFirstResponder()
// or -> phoneNumberTextField.resignFirstResponder()
}
override var inputAccessoryView: UIView? {
return toolBar
}
override var canBecomeFirstResponder: Bool {
return true
}