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.