1

我创建了一个按钮来打开 url 链接,但由于无法识别的选择器错误而失败。我通常会通过我在线阅读的方式将添加目标设置为 self,但是对于这个特定的实例,我收到错误:无法将 NSOBJECT ->() -> infoViewcontroller.infoview 类型的值转换为预期的参数类型 AnyObject。所以要解决这个问题,Xcode 建议将目标设置为 NSOBJECT.self。但是,这不再出现错误,而是在单击按钮时崩溃并返回原因:[NSObject displayWebLink]:无法识别的选择器发送到类 0x106011e58。所以我只是想知道这样做的正确方法是什么,为什么?下面是我的代码。

 class ActivityInfoView: UICollectionViewCell {


    var activity: ActivitysEvents? {

        didSet {
                       }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)

        setupViews()

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    var textView: UITextView = {
        let tv = UITextView()
        tv.userInteractionEnabled = false
        return tv
    }()

    let dividerLineView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.lightGrayColor()
        return view

    }()

    let urlLinkButton: UIButton = {
        let button = UIButton()
        button.backgroundColor = UIColor.redColor()
        button.titleLabel?.font = UIFont.systemFontOfSize(14)
        button.setTitleColor(UIColor.blueColor(), forState: .Normal)
       // button.addTarget(self, action: #selector(displayWebLink), forControlEvents: .TouchUpInside)
        button.addTarget(NSObject.self, action: #selector(displayWebLink), forControlEvents: .TouchUpInside)
        return button

    }()

   func displayWebLink() {
         print("abcdefghijklmnop")
    if let urlLink = activity?.url {
          //  UIApplication.sharedApplication().openURL(NSURL(string: urlLink)!)
            UIApplication.sharedApplication().openURL(NSURL(string:  urlLink)!, options: [:], completionHandler: nil)
           print("dhudududuhdu")
    }
    }

`

4

2 回答 2

1

这不是一个非常有用的错误消息。编译器正在尝试验证正确的对象是否使用名称定义了一个方法,displayWebLink并且它似乎使用闭包类型作为它正在搜索的上下文。

尝试告诉它在哪里可以找到方法:

button.addTarget(self, action: #selector(ActivityInfoView.displayWebLink), forControlEvents: .TouchUpInside)
于 2017-03-01T03:25:57.800 回答
0

我通过将按钮从“let”更改为“lazy var”来解决此问题,如下所示:

    lazy var urlLinkButton: UIButton = {
        let button = UIButton()
        button.backgroundColor = UIColor.redColor()
        button.titleLabel?.font = UIFont.systemFontOfSize(14)
        button.setTitleColor(UIColor.blueColor(), forState: .Normal)
        button.addTarget(self, action: #selector(displayWebLink), forControlEvents: .TouchUpInside)
        //button.addTarget(self(), action: #selector(ActivityInfoView.displayWebLink), forControlEvents: .TouchUpInside)
        return button

    }()
于 2017-03-03T20:14:05.890 回答