实现简单的分享功能
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
var textField:UITextField!
var buttonShare:UIButton!
var activityViewController:UIActivityViewController!
func handleShare(sender: UIButton){
guard let textFieldText = textField.text where
textFieldText.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).characters.count > 0 else{
let message = "Please enter a text and then press Share"
let alertController = UIAlertController(title: nil,
message: message,
preferredStyle: .Alert)
alertController.addAction(
UIAlertAction(title: "OK", style: .Default, handler: nil))
presentViewController(alertController, animated: true, completion: nil)
return
}
/* it is VERY important to cast your strings to NSString
otherwise the controller cannot display the appropriate sharing options */
activityViewController = UIActivityViewController(
activityItems: [NSString(string: textFieldText)],
applicationActivities: nil)
presentViewController(activityViewController,
animated: true,
completion: {
})
}
func textFieldShouldReturn(textField: UITextField) -> Bool{
textField.resignFirstResponder()
return true
}
func createTextField(){
textField = UITextField(frame:
CGRect(x: 20, y: 35, width: 280, height: 30))
textField.borderStyle = .RoundedRect;
textField.placeholder = "Enter text to share..."
textField.delegate = self
view.addSubview(textField)
}
func createButton(){
buttonShare = UIButton(type: .System)
buttonShare.frame = CGRect(x: 20, y: 80, width: 280, height: 44)
buttonShare.setTitle("Share", forState:.Normal)
buttonShare.addTarget(self,
action:"handleShare:",
forControlEvents:.TouchUpInside)
view.addSubview(buttonShare)
}
override func viewDidLoad() {
super.viewDidLoad()
createTextField()
createButton()
}
}
效果如下: