Reputation: 241
I have created a button to open url links and am failing with an unrecognised selector error. I would normally set the add target to be self just through how i have read online, but for this particular instance i get the error: cannot convert value of type NSOBJECT ->() -> infoViewcontroller.infoview to expected argument type AnyObject. So to get around this and what Xcode recommended was to set the target as NSOBJECT.self. However this no longer got an error but crashes upon the click of the button and returns the reason of: [NSObject displayWebLink]: unrecognized selector sent to class 0x106011e58. So i'm just wondering what the correct way of doing this would be and why? Below is my code.
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")
}
}
`
Upvotes: 1
Views: 85
Reputation: 241
I fixed this issue by changing the button from 'let' to 'lazy var' as below:
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
}()
Upvotes: 0
Reputation: 6635
That's not a very helpful error message. The compiler is trying to verify that the correct object defines a method with the name displayWebLink
and it seems to be using the closure type as the context where it's searching.
Try telling it where to find the method:
button.addTarget(self, action: #selector(ActivityInfoView.displayWebLink), forControlEvents: .TouchUpInside)
Upvotes: 1