【发布时间】:2020-10-31 10:39:29
【问题描述】:
免责声明:
在你撕下我的头并放火之前,我知道已经有人问过这样的问题,但它们都指的是单个按钮。 我有一个 collectionView。在仔细阅读所有其他问题并尝试将它们的解决方案结合在一起后,我提出了这个问题。
概述:
我正在创建一个带有集合视图的键盘扩展。在我的 collectionView 中,我有自定义单元格,在他们的类中我放置了一个按钮。我想为集合视图中的每个按钮添加一个目标。我知道我可以使用 selectItemAtIndexRow 函数并忽略按钮,但我需要处理 touchUpInside 和 touchDown 事件(因为当我使用 y 键盘键入时它非常慢)而且我还没有找到使用 collectionView 单元格的方法(如果存在的东西让我知道)。为了避免这个问题,我认为最好的解决方案是在我的单元格的类中添加一个按钮并添加我想要的操作,但我发现这样做有多个问题。
我在做什么:
-
我有经典的keyboardViewController,你可以通过创建一个新的键盘目标来放置一个视图(这是包含collectionView的视图)。
-
我有一个包含集合视图的自定义视图类
-
我有一个自定义的 collectionview 单元格类
自定义视图类
在这里,我以编程方式创建了我的 collectionView。
//Closure to add action to my buttons
var insertLowercase : ((IndexPath) -> ())?
let letters = ["q", "w", "e", "r", "t", "y", "u", "i", "o", "p"]
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
letters.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = keyView.dequeueReusableCell(withReuseIdentifier: "collectionCellId", for: indexPath) as! KeyboardKeys
cell.button.setTitle(letters[indexPath.row], for: .normal)
cell.button.addTarget(self, action: #selector(lettersKeyboard.insert(indexPath:)), for: .touchUpInside)
return cell
}
@objc func insert (indexPath: IndexPath){
insertLowercase?(indexPath)
}
这就是我添加目标的方式。但是,如果我按下按钮,键盘崩溃给我以下错误:
线程 1:“-[Keyboarddd.KeyboardButton 长度]:无法识别的选择器发送到实例 0x7f9bb2506740”
键盘视图控制器
将我的自定义视图放在这里后,在 viewDidLoad 我称之为:
letters.insertLowercase = { indexPath in
let text = self.letters.letters[indexPath.row]
self.textDocumentProxy.insertText(text)
} //And more stuff to handle quick insertion but this is what you need to reproduce my problem
问题:
我怎样才能体面地将目标添加到我的按钮?或者有没有办法直接对 collectionView 单元做我想做的事情?
【问题讨论】:
标签: ios swift uicollectionview uicollectionviewcell collectionview