Представление коллекции как пользовательская клавиатура не работает - PullRequest
1 голос
/ 18 марта 2019

Я создаю приложение, в котором у вас есть пользовательская клавиатура.

Внутри этого класса я создал представление коллекции, вот код:

class KeyboardViewController: UIInputViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, UICollectionViewDelegate {

let stickerImages = [
    UIImage(named: "Image-1"),
    UIImage(named: "Image-2"),
    UIImage(named: "Image-3"),
    UIImage(named: "Image-4"),
    UIImage(named: "Image-5")
]

@IBOutlet var nextKeyboardButton: UIButton!
@IBOutlet var collectionView: UICollectionView!

override func updateViewConstraints() {
    super.updateViewConstraints()
}

override func viewDidLoad() {
    super.viewDidLoad()

    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    layout.scrollDirection = UICollectionView.ScrollDirection.vertical
    layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    layout.itemSize = CGSize(width: 50, height: 50)

    collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
    collectionView.dataSource = self
    collectionView.delegate = self
    collectionView.register(StickersCell.self, forCellWithReuseIdentifier: StickersCell.reuseIdentifier)
    collectionView.backgroundColor = UIColor.white
    collectionView.showsHorizontalScrollIndicator = false
    collectionView.backgroundColor = UIColor.red

    collectionView.translatesAutoresizingMaskIntoConstraints = false

    self.view.addSubview(collectionView)

    self.nextKeyboardButton = UIButton(type: .system)

    self.nextKeyboardButton.setTitle(NSLocalizedString("Next Keyboard", comment: "Title for 'Next Keyboard' button"), for: [])
    self.nextKeyboardButton.sizeToFit()
    self.nextKeyboardButton.translatesAutoresizingMaskIntoConstraints = false
    self.nextKeyboardButton.backgroundColor = UIColor.white

    self.nextKeyboardButton.addTarget(self, action: #selector(handleInputModeList(from:with:)), for: .allTouchEvents)

    self.view.addSubview(self.nextKeyboardButton)

    self.nextKeyboardButton.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
    self.nextKeyboardButton.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true

    self.collectionView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
    self.collectionView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
    self.collectionView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
    self.collectionView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
}

override func textWillChange(_ textInput: UITextInput?) {
    // The app is about to change the document's contents. Perform any preparation here.
}

override func textDidChange(_ textInput: UITextInput?) {
    // The app has just changed the document's contents, the document context has been updated.

    var textColor: UIColor
    let proxy = self.textDocumentProxy
    if proxy.keyboardAppearance == UIKeyboardAppearance.dark {
        textColor = UIColor.white
    } else {
        textColor = UIColor.black
    }
    self.nextKeyboardButton.setTitleColor(textColor, for: [])
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return stickerImages.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: StickersCell.reuseIdentifier, for: indexPath) as! StickersCell

    cell.setImage(stickerImages[indexPath.item]!)

    return cell
}}

А вот и мой класс Collection View:

class StickersCell: UICollectionViewCell {

static let reuseIdentifier: String = "StickersCell"

lazy var imageView: UIImageView = {
    let imageView = UIImageView(frame: .zero)
    imageView.contentMode = .scaleAspectFit
    imageView.translatesAutoresizingMaskIntoConstraints = false
    return imageView
}()

override init(frame: CGRect) {
    super.init(frame: frame)
    contentView.clipsToBounds = true
    contentView.addSubview(imageView)

    imageView.leftAnchor.constraint(equalTo: contentView.leftAnchor).isActive = true
    imageView.rightAnchor.constraint(equalTo: contentView.rightAnchor).isActive = true
    imageView.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
    imageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
}

required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func setImage(_ image: UIImage) {
    imageView.image = image
}}

Этот код прекрасно работает при добавлении представления коллекции к любому UIView или UIViewController, но при попытке добавить его на клавиатуру выдает следующие ошибки:

Errors

Насколько я понимаю, я неправильно установил ограничения, но я не понимаю, что именно не так, особенно когда он работает нормально в простых представлениях или контроллерах представления.

Я гуглил и не мог найти решения ... Также не помогли эти вопросы:

  1. Первый вопрос
  2. Второй вопрос
  3. Третий вопрос

Я также пытался переместить код, который создает представление коллекции, в методы viewDidAppear и viewWillAppear, но тоже не повезло.

Еще одна странная вещь: Если я добавлю простой UIView с теми же ограничениями на клавиатуре - все работает нормально. Кажется, проблема связана с представлением коллекции.

Итак, что я пропустил? Был бы признателен за любую помощь, так как я борюсь с этой проблемой уже более недели ...

UPDATE:

Прочитав форумы разработчиков Apple, мне пришла в голову идея: Я создал UITableView так же, как UICollectionView раньше, и, как ни странно, это работает. Итак, есть следующий вопрос: Можно ли вообще использовать UICollectionView как пользовательскую клавиатуру?

1 Ответ

0 голосов
/ 01 апреля 2019

После борьбы с этой проблемой в течение 2 недель наконец-то нашел рабочий обходной путь:

Почему-то вы не можете использовать UIImageView или MSStickerView внутри UICollectionViewCell так же, как в iMessage Extension, поэтому вместо этого ятолько что добавил прозрачный UIButton с UIImage внутри этой кнопки, и это сработало!

Все еще не знаю, почему вы не можете использовать изображения или представления и не можете найти какую-либо конкретную информацию о нем, но мойРешения работают, и я надеюсь, что это поможет кому-то в будущем.

...