UI: 使用 UIActivityViewController 显示分享选项

问题:创建一个 UIActivityViewController 类的实例对象,通过该类进行内容分享 

 

在 iOS 中分享数据是很容易的。你需要做的就是使用 UIActivityViewController 类的方法 initWithActivityItems:applicationActivities:实例化一个对象,这个方法的参数如下: 

 

initWithActivityItems

这个 items 数组是你想要分享的内容。可以是 NSString,UIImage,或者任意遵循 UIActivityItemSource 协议的自定义类。 

applicationActivities 

 这是一个 UIActivity 实例数组,代表程序中支持的 activities。 

 例子:

创建文本框和按钮:

- (void)createTextField{
    self.textField = [[UITextField alloc]initWithFrame:CGRectMake(20, 35, 280, 30)];
    //?
    //self.textField.translatesAutoresizingMaskIntoConstraints = NO;
    self.textField.borderStyle = UITextBorderStyleRoundedRect;
    self.textField.placeholder = @"输入分享内容";
    self.textField.delegate = self;
    [self.view addSubview:self.textField];
    
}
- (void)createButton{
    self.buttonShare = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    //self.buttonShare.translatesAutoresizingMaskIntoConstraints = NO;
    self.buttonShare.frame = CGRectMake(20, 80, 280, 44);
    [self.buttonShare setTitle:@"Share`" forState:UIControlStateNormal];
    [self.buttonShare addTarget:self action:@selector(handleShare:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.buttonShare];
}

在viewDidLoad调用两个方法即可

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor whiteColor];
    [self createButton];
    [self createTextField];
}

点击键盘上的Return按钮隐藏键盘

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

点击share按钮调用的方法:将内容通过UIActivityViewController进行分享:

- (void)handleShare:(id)paramSender{
    if ([self.textField.text length]== 0) {
        NSString *message = @"Please enter a text and then press Share";
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:nil message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alertView show];
        return;
    }
//重要
    self.activityViewController = [[UIActivityViewController alloc]initWithActivityItems:@[self.textField.text] applicationActivities:nil];
    [self presentViewController:self.activityViewController animated:YES completion:^{
        
    }];
}

 

posted @ 2014-10-11 10:09  safiri  阅读(719)  评论(0编辑  收藏  举报