【问题标题】:UIButton unrecognized selector sent to instance [duplicate]UIButton无法识别的选择器发送到实例[重复]
【发布时间】:2017-05-22 21:58:28
【问题描述】:

我正在使用带有 UICollectionView 的自定义单元格,我需要以编程方式为每个单元格定义 UIButton。

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! ClinicListCell
    cell.title.text = clinicNames[indexPath.row]
    cell.subTitle.text = clinicSubs[indexPath.row]
    cell.backgroundImageView.image = UIImage(named: clinicImages[indexPath.row])
    cell.profileBtn.tag = indexPath.row
    cell.profileBtn.addTarget(self, action: Selector(("profileBtnClicked:")), for: .touchUpInside)
    return cell
}

并且我在同一个类中定义了以下选择器方法。

class func profileBtnClicked(sender:UIButton) {
    print("Selected")
}

我尝试从选择器方法中删除类/静态,但它总是给我unrecognized selector sent to instance 错误,我哪里出错了?

谢谢。

【问题讨论】:

标签: ios swift uibutton


【解决方案1】:
Try this 
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! ClinicListCell
    cell.title.text = clinicNames[indexPath.row]
    cell.subTitle.text = clinicSubs[indexPath.row]
    cell.backgroundImageView.image = UIImage(named: clinicImages[indexPath.row])
    cell.profileBtn.tag = indexPath.row
    cell.profileBtn.addTarget(self, action: #selector(YourViewController.profileBtnClicked(sender:)), for: UIControlEvents.touchUpInside)
    return cell
}


class func profileBtnClicked(sender:UIButton) {
    print("Selected")
}

【讨论】:

  • 谢谢,这行得通。
  • 抱歉,class func 限定符是错误的。您需要一个 instance 方法,否则您将无法访问视图控制器的属性和方法。
  • 如果您解释问题,而不是仅发布代码,则答案会更有帮助(对问题的作者和该线程的未来读者)。 OP 的代码有什么问题,如何解决?
【解决方案2】:

profileBtn 是否可能已关联?当名称已更改或界面生成器中的按钮与变量之间的链接被删除时,可能会发生此错误。

或者你可以试试语法

cell.profileBtn.addTarget(self, action: #selector("profileBtnClicked:"), for: .touchUpInside)

【讨论】:

  • 如果它没有链接起来,它不应该抛出我无法识别的选择器错误,对吧?从我理解的错误来看,它找不到选择器方法。
【解决方案3】:

尝试将@objc 添加到您的方法中,在这种情况下并非严格要求,并删除classstatic 限定符。

顺便说一句,从 Swift 2.2 开始,您可以使用 #selector 运算符从 Swift 函数中创建 Selector。例如:

let clicked = #selector(self.profileBtnClicked(sender:))

为:

@objc func profileBtnClicked(sender: UIButton) {
    ...
}

从技术上讲,对于基于 NSObject 的类,@obj 限定符应该只用于 private 方法。

【讨论】:

  • 两个都试过了,都不行。
  • @IbrahimAzharArmar 你试过@objc#selector 的组合吗?我更新了我的答案...
猜你喜欢
  • 1970-01-01
  • 2021-04-27
  • 1970-01-01
  • 1970-01-01
  • 2021-11-10
  • 2017-01-26
  • 1970-01-01
  • 2013-05-18
  • 2012-06-13
相关资源
最近更新 更多