所以我一直在四处寻找有关如何执行此操作的指南,但我担心我会遇到空白!
所以基本上我想使用 Swift 为 iOS 创建一个简单的表情符号/图像/gif 键盘扩展。
对于我的主要应用程序的一部分,我有一个 viewController,其中包含一个 collectionView 和一个 collectionViewCell。使用 plist 中的信息,我生成了一个图像集合(父组),当被选中时,它会向下钻取到第二层,显示该组的所有图像。从此级别选择图像会将图像复制到剪贴板。
所以我已经把这个主要的应用程序部分做得非常好,现在想模仿键盘的功能。
所以我做了一个键盘扩展,它创建了一个 class KeyboardViewController: UIInputViewController
文件。
然后,我创建了一个名为 Keyboard.xib
的新 View 文件。在 View 中,我添加了一个 UICollectionView
。
在 KeyboardViewController
中,我调用
override func viewDidLoad() {
super.viewDidLoad()
let nib = UINib(nibName: "Keyboard", bundle: nil)
let objects = nib.instantiateWithOwner(self, options: nil)
view = objects[0] as! UIView
addKeyboardButtons()
}
当应用程序运行时,它会在键盘 View 中显示我的空 collectionView。
我现在的挑战是用一个可重用的单元格填充 collectionView,该单元格将显示来自 plist 文件中名称的图像。
在我的主应用程序中,我能够确定 collectionView 中的项目数,这为我创建了一个单元格。
但是,在键盘 View 中,我没有添加单元格的选项。将单元格拖到 collectionView 中也无济于事。
所以我只是想知道,将可重复使用的单元格放入 Keyboard.xib
中的 collectionView 中的最佳方法是什么,然后我可以用图像填充它?
我从一篇旧帖子的某个地方读到有人创建了一个新的 xib
文件,纯粹是他的单元格,其中包含一个 imageView
,并使用了那个 xib
单元格文件以填充到 collectionView
中。
我已经创建了那个额外的 xib
文件,但不确定如何建立连接以使其在 collectionView 中用作可重用单元...
有什么想法或想法吗?
谢谢!!!
最佳答案
我通过为我的 Keyboard.xib
创建一个新的类文件,并在其中创建和设置 collectionView socket 和委托(delegate)来解决这个问题。
class KeyboardView: UIView, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var collectionView: MyCollectionView!
class func instanceFromNib() -> KeyboardView {
return UINib(nibName: "Keyboard", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! KeyboardView
}
override func awakeFromNib() {
print("awaking from nib")
collectionView.delegate = self
collectionView.dataSource = self
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print("adding numberOfItemsForSection")
return 1
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
print("adding cell")
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("myCell", forIndexPath: indexPath)
cell.backgroundColor = UIColor.greenColor()
return cell
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
print("setting size..")
return CGSizeMake(320, 350)
}
}
然后更新我的 KeyboardViewController.swift
文件来实例化
override func viewDidLoad() {
super.viewDidLoad()
let keyboardView = KeyboardView.instanceFromNib()
keyboardView.collectionView.registerNib(UINib.init(nibName: "Cell", bundle: nil), forCellWithReuseIdentifier: "myCell")
self.view.addSubview(keyboardView)
addKeyboardButtons()
}
谢谢!
关于ios - 使用 CollectionView 和 CollectionViewCells 创建 Swift iOS 9 自定义键盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35347038/