移動App開發時經常會遇到分享的需求,iOS內建的UIActivityViewController就是一個不錯的方式數組
UIActivityViewController的構造方法以下app
public init(activityItems: [AnyObject], applicationActivities: [UIActivity]?)
activityItems: [AnyObject]
這個參數是一個AnyObject類型數組,其內容是你但願分享的任意內容,能夠是NSString、UIImage或其餘遵循UIActivityItemSource Protocol的類ide
applicationActivities: [UIActivity]?
這個參數表示了此應用自身能處理的分享類型,這裏能夠聲明應用是否能夠處理自身的分享spa
這裏咱們經過一個Demo來演示一下UIActivityViewController的使用方法
首先咱們建立一個UITextField和一個分享按鈕code
lazy var textField:UITextField = { var textField = UITextField(frame: CGRect(x: 20, y: 35, width: 280, height: 30)) textField.borderStyle = .RoundedRect textField.delegate = self return textField }()
lazy var shareButton:UIButton = { var shareButton = UIButton(frame: CGRect(x: 20, y: 20, width: 280, height: 44)) shareButton.setTitle("Share", forState: .Normal) shareButton.addTarget(self, action: Selector("share"), forControlEvents: .TouchUpInside) return shareButton }()
而後在視圖中添加控件,並實現TextField的Delegate方法 最後咱們來寫分享的方法
func share(){ if ((textField.text?.isEmpty) != nil){ print("無分享信息") return } let activityViewController = UIActivityViewController(activityItems: [textField.text! as NSString], applicationActivities: nil) presentViewController(activityViewController, animated: true) { () -> Void in } }