请不要将这个问题标记为重复,因为我已经尝试过各种解决方案,但效果不佳。我在FormViewController中创建一个headerView(我正在使用Eureka),并将视图分成单独的HeaderViews: NSObject以遵守MVC原理。我试图添加一个buttonTarget,但它抛出错误unrecognized selector sent to class。我的代码如下:

class ProfileSettingsViewController: FormViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        form +++

            Section(){ section in
                section.header = {
                    var header = HeaderFooterView<UIView>(.callback({
                        let view = HeaderViews.setUpHeaderForProfileView(user: self.user)
                        return view
                    }))
                    header.height = { 200 }
                    return header
                }()
            }
        }

在我的HeaderViews中:
class HeaderViews: NSObject {

    static func setUpHeaderForProfileView(user: User) -> UIView {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: screen.width, height: 100))
        let changeAvatarButton = UIButton(frame: CGRect(x: (screen.width / 2) - 50, y: avatarImageView.frame.maxY + 10, width: 100, height: 20))
        changeAvatarButton.addTarget(self, action: #selector(getAvatar(_:)), for: .touchUpInside)
        view.addSubview(changeAvatarButton)
        return view
    }

    func getAvatar(_ sender: UIButton!) {
        print("Change Avatar tapped")
    }
}

我不太确定自己是否犯了任何错误,因为我在本文中尝试了各种选择器方法:Unrecognized selector sent to class

我怀疑这可能与子类NSObject有关。有什么建议吗?

最佳答案

更新
如果您无法获得HeaderViews的实例。然后只需将getAvatar更改为静态函数即可。

static func getAvatar(_ sender: UIButton!) {
    print("Change Avatar tapped")
}

来源
在静态函数中,不应将self用作目标。
因为此self表示HeaderViews
将实例传递给目标。

例如:
static func setUpHeaderForProfileView(user: User, in instance: HeaderViews) -> UIView {
    let view = UIView(frame: CGRect(x: 0, y: 0, width: screen.width, height: 100))
    let changeAvatarButton = UIButton(frame: CGRect(x: (screen.width / 2) - 50, y: avatarImageView.frame.maxY + 10, width: 100, height: 20))
    changeAvatarButton.addTarget(instance, action: #selector(getAvatar(_:)), for: .touchUpInside)
    view.addSubview(changeAvatarButton)
    return view
}

10-08 06:29