Search code examples
iosswiftfbsdkfbsdksharekit

How to create a custom share button in Facebook SDK


I try to create custom share Button in Facebook SDK, but I have a problem with it. Following Facebook documentation, share Button in my case looks like that:

let content = FBSDKShareLinkContent()
content.contentTitle = "\(postTitle)"
content.contentURL = NSURL(string:"\(www)")

let shareButton = FBSDKShareButton()
shareButton.shareContent = content
shareButton.center = selfview.center
self.view.addSubiview(shareButton)

it works, but I have a default button, which doesn't look good in my layout. I would like to have a possibility share my content using my own button facebookShareButton: UIButton. Do I have a possibility to call this action in my own button? If yes, how can I do that?


Solution

  • I have a solution for this problem:

    We need to create an UIButton outlet for example @IBOutlet weak var facebookOutlet: UIButton! and then add code in viewDidLoad()

      facebookOutlet.addTarget(self, action: #selector(ViewController.postFacebook(_:)), forControlEvents: .TouchUpInside)
    

    Then in viewDidAppear() we need to add:

    let content = FBSDKShareLinkContent()
    content.contentTitle = "\(postTitle)"
    content.contentURL = NSURL(string:"\(www)")
    
    let shareButton = FBSDKShareButton()
    shareButton.shareContent = content
    shareButton.center = self.view.center
    self.view.addSubview(shareButton)
    

    Then in action of our button we need to add:

    func postFacebook(sender: UIButton){
        shareButton.sendActionsForControlEvents(.TouchUpInside)
    }
    

    It works perfect and allow us to create a custom facebook button.