需要实例化UIActivityViewController这个类,通过initWithActivityItems:applicationActivities: 方法:
initWithActivityItems:要分享的东西,可以是NSString, UIImage, 自己定义的符合UIActivityItemSource 协议的类的实例。
applicationActivities:代表这项分享的动作你自动的应用可以支持
将用户输入的文字发送到UIActivityViewController类的实例化
头文件
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UITextFieldDelegate>
@end
实现文件
#import "ViewController.h"
@interfaceViewController ()
@property(nonatomic,strong) UITextField *textField;
@property(nonatomic,strong) UIButton *buttonShare;
@property(nonatomic,strong) UIActivityViewController *acticityViewController;
@end
@implementation ViewController
- (void) createTextField {
self.textField = [[UITextFieldalloc] initWithFrame:CGRectMake(20.0f, 30.0f, 280.0f, 30.0f)];
self.textField.translatesAutoresizingMaskIntoConstraints = NO;
self.textField.borderStyle = UITextBorderStyleRoundedRect;
self.textField.placeholder = @"Enter Text to share";
self.textField.delegate = self;
[self.view addSubview:self.textField];
}
- (void) createButton {
self.buttonShare = [UIButtonbuttonWithType:UIButtonTypeRoundedRect]; //子类用这个方法不能返回一个button
self.buttonShare.translatesAutoresizingMaskIntoConstraints = NO;
self.buttonShare.frame = CGRectMake(20.0f, 80.0f, 280.0f, 35.0f);
[self.buttonSharesetTitle:@"Share"forState:UIControlStateNormal];
[self.buttonShareaddTarget:selfaction:@selector(handlerShare:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.buttonShare];
}
//UITextFieldDelegate中的方法,用于dismiss keyboard
- (BOOL) textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
returnYES;
}
- (void) handlerShare: (id)paramSender {
if ([self.textField.text length] == 0) {
NSString *message = @"please enter a text and then press the share button";
UIAlertView *alertView =[[UIAlertViewalloc] initWithTitle:nilmessage:message delegate:nilcancelButtonTitle:@"OK"otherButtonTitles: nil];
[alertView show];
return;
}
self.acticityViewController = [[UIActivityViewControlleralloc]initWithActivityItems:@[self.textField.text]applicationActivities:nil];
[selfpresentViewController:self.acticityViewControlleranimated:NOcompletion:^{
}];
}
- (void)viewDidLoad
{
[superviewDidLoad];
[selfcreateTextField];
[selfcreateButton];
}
- (void)didReceiveMemoryWarning
{
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
运行图