iOS开发之UITextView自定义选择内容后的分享菜单

注意:只有重写了UIRespondercanPerformAction: withSender:方法,且该方法的返回值是YES时,才会显示该Action对应的控件,并且用户在UITextView中选中的文本长度大于0,才会返回YES。



//

//  ViewController.m

//  1113UITextView之自定义选择内容后的菜单

//

//  Created by weibiao on 15/11/13.

//  Copyright © 2015 weibiao. All rights reserved.

//


#import "ViewController.h"


@interface ViewController ()

@property (weak, nonatomic) IBOutlet UITextView *textView;


@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    

    // create two menuitem

    UIMenuItem *mailShare = [[UIMenuItem alloc] initWithTitle:@"邮件分享" action:@selector(mailShare:)];

    UIMenuItem *weiboShare = [[UIMenuItem alloc] initWithTitle:@"微博分享" action:@selector(weiboShare:)];

    // create UIMenuController

    UIMenuController *menu = [UIMenuController sharedMenuController];

    // add two menuitem for UIMenuController

    [menu setMenuItems:[NSArray arrayWithObjects:mailShare,weiboShare, nil]];

}

// 重写UIRespondercanPerformAction: withSender:

// Allows an action to be forwarded to another target. By default checks -canPerformAction:withSender: to either return self, or go up the responder chain.


// 当该方法返回yes时,该界面将会显示Action对应的控件

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {

    // 如果ActionmailShare:或weiboShare:方法

    if (action == @selector(mailShare:) || action == @selector(weiboShare:)) {

        // 如果textView选中的内容长度大于0,返回yes

        // 当该方法返回yes时,该Action对应的控件将会显示出来

        if (self.textView.selectedRange.length > 0 ) {

            return YES;

        }

    }

    return NO;

}


- (void)mailShare:(id)sender {

    NSLog(@"模拟邮件分享");

}

- (void)weiboShare:(id)sender {

    NSLog(@"模拟微博分享");

}

@end


iOS开发之UITextView自定义选择内容后的分享菜单_第1张图片

你可能感兴趣的:(iOS开发之UITextView自定义选择内容后的分享菜单)