UIWebView自定义菜单栏

我的博客原文地址

主要代码

CustomWebView.h

@interface CustomWebView : UIWebView


@end

CustomWebView.m

#import "CustomWebView.h"

@implementation CustomWebView

-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        // 全代码时入口
        [self addMenu];
    }

    return self;
}

-(void)awakeFromNib
{
    [super awakeFromNib];

    // xib时入口
    [self addMenu];
}

- (void)addMenu
{
    UIMenuController *menuController = [UIMenuController sharedMenuController];

    UIMenuItem *menuItemCopy = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(copyT:)];

    UIMenuItem *menuItemNote = [[UIMenuItem alloc] initWithTitle:@"笔记" action:@selector(noteT:)];

    UIMenuItem *menuItemSearch = [[UIMenuItem alloc] initWithTitle:@"搜索" action:@selector(searchT:)];

    UIMenuItem *menuItemShare = [[UIMenuItem alloc] initWithTitle:@"分享" action:@selector(shareT:)];

    NSArray *mArray = [NSArray arrayWithObjects:menuItemCopy,menuItemNote,menuItemSearch,menuItemShare,nil];
    [menuController setMenuItems:mArray];
}

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    if(action == @selector(copyT:) || action == @selector(noteT:) || action == @selector(searchT:) || action == @selector(shareT:))
    {
        return YES;
    }

    return NO;
}

-(void)copyT:(id)sender
{
    NSLog(@"复制");
}

-(void)noteT:(id)sender
{
    NSLog(@"笔记");
}

-(void)searchT:(id)sender
{
    NSLog(@"搜索");
}

-(void)shareT:(id)sender
{
    NSLog(@"分享");
}

@end

代码示例

    CustomWebView *webview = [CustomWebView new];
    webview.frame = self.view.bounds;
    [self.view addSubview:webview];
    NSURL *url = [NSURL URLWithString:@"http://www.feheadline.com/webapp/detail.html?id=3374280"];
    NSURLRequest *req = [[NSURLRequest alloc] initWithURL:url];
    [webview loadRequest:req];

刚开始在CustomWebView.m的initWithFrame方法中,但是长按后菜单栏一直没有出来,后来发现,如果是通过xib添加此控件的话,通过断点跟踪就可发现,它是不会执行initWithFrame方法的,所以那段代码应该写在-(void)awakeFromNib方法中,如果是通过代码添加的,就应该写在initWithFrame方法中,否则不执行添加菜单的操作。

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender这个方法可以筛选出需要的菜单项,而自定义的WebView中已经重写了这个方法,所以在webview中弹出的菜单是需要的菜单项,在其他控件中例如TextField控件,弹出的依旧会是系统默认的菜单项,只是出于程序可读性,可维护性考虑,最好在自定义的控件中修改菜单性,单独封装起来。

图片示例:

uiwebview-menu-1

完整代码下载

参考

http://jingyan.baidu.com/article/ac6a9a5e7d3e282b653eac1b.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值