Atarang
Atarang

Reputation: 422

swift UIViewController for a button in a custom cell

I've a custom table view cell which has a label view. I added tapGesture to invoke a function when that view is clicked. Currently my custom view cell is in it's own swift file. I added following code to enable 'Share extension' when clicked on that label.

  CustomCellView.swift

  10 myLabel.isUserInteractionEnabled = true
  11 let tap = UITapGestureRecognizer(target: self, action: #selector(tapLabelGesture))
  12 myLabel.addGestureRecognizer(tap)

  13 func tapLabelGesture() {
  14   print("Clicked on Label ")
       let url="www.google.com"
  15   let activityVC = UIActivityViewController(activityItems: [url], applicationActivities: nil)

  16   activityVC.popoverPresentationController?.sourceView = self.view
  17   self.present(activityVC, animated: true, completion: nil)
  18 }

I get compiler error on line 16 for self.view and 17 for self.present(). Question is how do I provide view for the popup?

This code I used for another view (without table view or cell) as a test and it worked fine. So I'm trying do the same technique for a tableview/cell. How do I resolve this issue? Any help is appreciated.

Upvotes: 0

Views: 87

Answers (3)

Atarang
Atarang

Reputation: 422

I got more ideas from this thread on SO, how to recognize label click on custom UITableViewCell - Swift 3 With the an extension, I was able to solve this issue.

Upvotes: 0

Tomasz Pe
Tomasz Pe

Reputation: 716

As @DharmeshKheni mentioned you cannot use a subclass of UITableViewCell like UIViewController. It doesn't provide view property and present method.

Answering your question, you could store a closure in the CustomCellView:

var onLabelTappedCallback: (() -> Void)?

call it in your selector:

@objc private func tapLabelGesture() {
    onLabelTappedCallback?()
}

and finally implement in the cellForRowAt method:

cell.onLabelTappedCallback = {
    print("Label tapped")
    //Present additional vc
}

This solution will work with UIButton as well.

Upvotes: 0

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71854

For line 16:

You are getting an error which says your class CustomCellView has no member view because your class is subclass of UITableViewCell not UIViewController because UIViewController has that property and your CustomCellView have contentView for that.

For line 17:

same as above your class is not subclass of UIViewController thats why you can not use self.present for that.

Solution:

Instead of using UITapGestureRecognizer you can use UIButton which you can place on UILabel and in your UIViewController class add button.tag and button.addTarget in your cellForRowAt method.

Then you can add your code in your button method and present UIActivityViewController.

Hope this will help.

Upvotes: 1

Related Questions