重新加载输入视图时,输入附件视图无法正确调整位置

时间:2019-01-28 00:05:26

标签: swift iphone-x inputaccessoryview

在iPhone X上运行我的应用程序时,我遇到了自定义输入附件视图的问题。在iPhone X上的自定义输入视图和系统键盘之间切换时,自定义附件视图将不会固定在屏幕顶部尺寸变化时,键盘变得模糊不清或留有很大的空隙。如何避免这种情况?

在引入iPhone X之前,我从来没有遇到过这个问题。配件似乎应该自动固定到键盘上,而无需任何其他代码。

import UIKit

class ViewController: UIViewController {

lazy var input: TextInput = {
    let input = TextInput(frame: CGRect(origin: .zero, size: CGSize(width: self.view.bounds.width, height: 200)))
    input.backgroundColor = #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 0.7024097711)
    input.autoresizingMask = [.flexibleHeight]
    return input
}()

lazy var accessory: TextAccessory = {
    let accessory = TextAccessory(frame: CGRect(origin: .zero, size: CGSize(width: self.view.bounds.width, height: 60)))
    accessory.backgroundColor = #colorLiteral(red: 0.9607843161, green: 0.7058823705, blue: 0.200000003, alpha: 0.7)
    accessory.autoresizingMask = [.flexibleHeight]
    accessory.control.addTarget(self, action: #selector(controlChanged(sender:)), for: .valueChanged)
    accessory.control.selectedSegmentIndex = 1
    return accessory
}()

@IBOutlet var textView: UITextView?

override func viewDidLoad() {
    super.viewDidLoad()
    textView?.inputView = input
    textView?.inputAccessoryView = accessory
}

@objc func controlChanged(sender: Any?) {
    textView?.inputView = accessory.control.selectedSegmentIndex == 1 ? input : nil
    textView?.reloadInputViews()
}
}

class TextInput: UIView {

lazy var button: UIButton = {
    let b = UIButton(type: .system)
    b.setTitle("Test", for: .normal)
    self.addSubview(b)
    return b
}()

override func layoutSubviews() {
    super.layoutSubviews()
    let size = button.sizeThatFits(bounds.size)
    button.bounds = CGRect(origin: .zero, size: size)
    button.center = CGPoint(x: bounds.midX, y: bounds.midY)
}
}

class TextAccessory: UIView {

lazy var control: UISegmentedControl = {
    let c = UISegmentedControl(items: ["Keyboard", "Custom"])
    self.addSubview(c)
    return c
}()

override func layoutSubviews() {
    super.layoutSubviews()
    let size = control.sizeThatFits(bounds.size)
    control.bounds = CGRect(origin: .zero, size: size)
    control.center = CGPoint(x: bounds.midX, y: bounds.midY)
}
}

输入附件视图应自动固定键盘顶部,但是在标准键盘和自定义输入视图之间来回切换时,附件视图将出现在键盘顶部上方或下方。

指向包含整个示例项目的GitHub存储库的链接如下: https://github.com/pmodernme/Input-View-Switch

0 个答案:

没有答案