如何创建标准的iOS Share按钮?

问题描述 投票:36回答:7

The iOS Human Interface Guidelines say

使用系统提供的“共享”按钮。用户熟悉此按钮的含义和行为,因此在可能的情况下使用它是个好主意。主要的例外是如果您的应用程序不包含工具栏或导航栏[,因为]共享按钮只能在工具栏或导航栏中使用。

好的,但我如何“使用系统提供的共享按钮”? A search of the documentation没有任何用处。

我收集了I should use UIActivityViewController in my response to the button being tapped,但我怎么能首先创建标准的Share按钮?

ios cocoa-touch ios7 uikit share
7个回答
40
投票

标准的共享按钮是一个UIBarButtonItem(因此它只能在导航栏或工具栏上)。你需要create a “system item”;特别是,an “action item”。 “操作”栏按钮项是“共享”按钮。


27
投票

这是代码。我假设你在ViewController里面,所以self有navigationItem属性。

UIBarButtonItem *shareButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemAction
                     target:self
                     action:@selector(shareAction:)];
self.navigationItem.rightBarButtonItem = shareButton;

13
投票

这在你的viewDidLoad中:

UIBarButtonItem *shareButton = [[UIBarButtonItem alloc]
                                initWithBarButtonSystemItem:UIBarButtonSystemItemAction
                                target:self
                                action:@selector(compartir:)];
self.navigationItem.rightBarButtonItem = shareButton;

并将您的选择器方法定义为action(在我的例子中命名为“compartir”):

- (void) compartir:(id)sender{

//Si no


NSLog(@"shareButton pressed");


NSString *stringtoshare= @"This is a string to share";
UIImage *imagetoshare = img; //This is an image to share.

NSArray *activityItems = @[stringtoshare, imagetoshare];
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
activityVC.excludedActivityTypes = @[UIActivityTypeAssignToContact, UIActivityTypePrint, UIActivityTypePostToTwitter, UIActivityTypePostToWeibo];
[self presentViewController:activityVC animated:YES completion:nil];
}

6
投票

Main.storyboard - > Bar Button Item - > Inspector - > System Item选择“Action”enter image description here


3
投票

这是Swift 3的代码。

func addShareBarButtonItem() {

    let shareButton = UIBarButtonItem(barButtonSystemItem: .Action, target: self, action: #selector(MyViewController.shareButtonPressed))

    self.navigationItem.rightBarButtonItem = shareButton
}

func shareButtonPressed() {
    //Do something now!
}

2
投票

系统提供的Action按钮也可以使用Interface Builder完全创建。为此,只需将UIToolbar拖放到视图中即可。然后将UIBarButtonItem拖放到UIToolbar中。下一步在视图层次结构中选择UIBarButtonItem,转到Attribute Inspector并选择“Action”作为System Item。完成!

此外,可以将UIBarButtonItem与您的类连接为IBOutlet或IBAction。

请注意:我使用Xcode 7作为参考。


1
投票

对于swift 4 / Xcode 10,只有我的两美分:

1)动作的初始字符改变了:

let shareButton = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(shareButtonPressed))

2)添加@obj:

@objc func shareButtonPressed() {
    //Do something now!
}
© www.soinside.com 2019 - 2024. All rights reserved.