Build: Share Sheet Demo
This screen shows a button that opens the iOS share sheet to share a text message.
Target UI
------------------------- | Share Sheet Demo | |-----------------------| | | | [Share Text] | | | -------------------------
------------------------- | Share Sheet Demo | |-----------------------| | | | [Share Text] | | | -------------------------
import UIKit class ShareSheetViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemBackground // TODO: Add Share Text button and action } }
import UIKit class ShareSheetViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemBackground let shareButton = UIButton(type: .system) shareButton.setTitle("Share Text", for: .normal) shareButton.titleLabel?.font = UIFont.systemFont(ofSize: 20, weight: .medium) shareButton.translatesAutoresizingMaskIntoConstraints = false shareButton.addTarget(self, action: #selector(shareText), for: .touchUpInside) view.addSubview(shareButton) NSLayoutConstraint.activate([ shareButton.centerXAnchor.constraint(equalTo: view.centerXAnchor), shareButton.centerYAnchor.constraint(equalTo: view.centerYAnchor) ]) } @objc func shareText() { let textToShare = "Hello from my app!" let activityVC = UIActivityViewController(activityItems: [textToShare], applicationActivities: nil) // For iPad: set popover source if let popover = activityVC.popoverPresentationController { popover.sourceView = self.view popover.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0) popover.permittedArrowDirections = [] } present(activityVC, animated: true) } }
We create a UIButton labeled 'Share Text' and center it using Auto Layout. When tapped, it triggers shareText() which creates a UIActivityViewController with the text to share. For iPad compatibility, we set the popoverPresentationController sourceView and sourceRect to avoid crashes and show the share sheet properly as a popover.
This approach uses standard UIKit patterns and ensures the share sheet works on all iOS devices.
------------------------- | Share Sheet Demo | |-----------------------| | | | [Share Text] | | | -------------------------
UIActivityViewController in an iOS app?UIActivityViewController with a text string to share?UIActivityViewController(activityItems: [Any], applicationActivities: [UIActivity]?).let textToShare = "Check this out!" let activityVC = UIActivityViewController(activityItems: [textToShare], applicationActivities: nil) present(activityVC, animated: true)
let image = UIImage(named: "photo.png") let activityVC = UIActivityViewController(activityItems: [image], applicationActivities: nil) present(activityVC, animated: true)
UIActivityViewController. Which code snippet correctly sets this up and presents the share sheet?Pass the test and this pattern moves unknown