如何在iOS中通过键盘显示UIView

问题描述 投票:9回答:7

当用户点击inputAccessoryView中的“附加”按钮时,我想在键盘上创建一个简单的视图。像这样的东西:

enter image description here

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

ios swift uiview uikeyboard
7个回答
13
投票

您可以将新子视图添加到应用程序窗口。

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);
}

4
投票

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)

3
投票

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中的最后一个窗口。


3
投票

您是否找到了解决此问题的有效方法?在iOS9中,您将customView放在窗口的顶部:

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

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


2
投票

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


2
投票

正如TamásSengel所说,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()
}

解释图片:enter image description here

方法2:带图像的结果

enter image description here

在表视图控制器中 - 在底部添加严格视图

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

override var inputAccessoryView: UIView? {
    return toolBar
}

override var canBecomeFirstResponder: Bool {
    return true
}

0
投票

虽然这可以访问最顶层的窗口,但我会避免这样做,因为它明显干扰了Apple的指导方针。

我要做的是解雇键盘并用相同尺寸的视图替换它的框架。

键盘的框架可以从here列出的键盘通知中访问,他们的userInfo包含一个可以用UIKeyboardFrameEndUserInfoKey访问的密钥。

© www.soinside.com 2019 - 2024. All rights reserved.