无法识别的选择器发送到 UIButton 中的实例
Unrecognized selector sent to instance in UIButton
我里面有一个集合视图和图像视图,我添加了一个UIButton
来在选择后删除图像。当我点击按钮时它崩溃并给我这个错误:
AdPostViewController deleteUser]: unrecognized selector sent to instance 0x7fb588d5b7f0
为什么会发生这种情况,我该如何解决?这是我的代码:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! ImageCell
let img = self.PhotoArray[indexPath.row]
cell.image.image = img
cell.deleteButton?.layer.setValue(indexPath.row, forKey: "index")
cell.deleteButton?.addTarget(self, action: Selector(("deleteUser")), for: UIControl.Event.touchUpInside)
return cell
}
func deleteUser(_ sender: UIButton) {
let i: Int = (sender.layer.value(forKey: "index")) as! Int
PhotoArray.remove(at: i)
// PhotoArray.removeAtIndex(i)
ImagesCollectionView.reloadData()
}
一个问题是您强制手动形成 Objective-C 选择器,而您实际上并不知道如何手动形成 Objective-C 选择器,所以您弄错了。不要那样做!让编译器为您形成选择器。那是它的工作。替换
action: Selector(("deleteUser"))
和
action: #selector(deleteUser)
此外,您需要将 deleteUser
方法显式公开给 Objective-C:
@objc func deleteUser(_ sender: UIButton) {
否则Objective-C仍然无法反省你的class并在调用它的时候找到这个方法。幸运的是,当您切换到 #selector
语法时,编译器会为您指出该问题!
我里面有一个集合视图和图像视图,我添加了一个UIButton
来在选择后删除图像。当我点击按钮时它崩溃并给我这个错误:
AdPostViewController deleteUser]: unrecognized selector sent to instance 0x7fb588d5b7f0
为什么会发生这种情况,我该如何解决?这是我的代码:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! ImageCell
let img = self.PhotoArray[indexPath.row]
cell.image.image = img
cell.deleteButton?.layer.setValue(indexPath.row, forKey: "index")
cell.deleteButton?.addTarget(self, action: Selector(("deleteUser")), for: UIControl.Event.touchUpInside)
return cell
}
func deleteUser(_ sender: UIButton) {
let i: Int = (sender.layer.value(forKey: "index")) as! Int
PhotoArray.remove(at: i)
// PhotoArray.removeAtIndex(i)
ImagesCollectionView.reloadData()
}
一个问题是您强制手动形成 Objective-C 选择器,而您实际上并不知道如何手动形成 Objective-C 选择器,所以您弄错了。不要那样做!让编译器为您形成选择器。那是它的工作。替换
action: Selector(("deleteUser"))
和
action: #selector(deleteUser)
此外,您需要将 deleteUser
方法显式公开给 Objective-C:
@objc func deleteUser(_ sender: UIButton) {
否则Objective-C仍然无法反省你的class并在调用它的时候找到这个方法。幸运的是,当您切换到 #selector
语法时,编译器会为您指出该问题!