How to add custom menu item to UITextView menu, which is a link to the Wikipedia page of the selected word?

有些话、适合烂在心里 提交于 2019-12-20 19:36:54

问题


I am new to Xcode, I am using version 4.6.3 - Macbook too old for the new version.

I looked around the internet and Stack Overflow and cannot find what I want or I cannot get snippets to work.

I would like to add a menu item to the menu items that appear when longpressing a word in a UITextView. I want it to say "Wiki" and when this is pressed, it will link to the wikipedia page of the word that is selected. It may be through Safari or should I do this within the app with a webview?

I found:

UIMenuController *menuController = [UIMenuController sharedMenuController];
UIMenuItem *item1 = [[UIMenuItem alloc] initWithTitle:@"Do This" action:@selector(item1)];
[menuController setMenuItems:[NSArray arrayWithObject:item1]];

But this didn't seem to do anything.

Unfortunately I cannot understand the suggestions for retrieval of a wkipedia page, I am not that advanced, sorry. I usually do not know where to put the code snippets.

The UILabel I have displays the text better, the text in the rectangular UITextView has a gap at the top so the text is not centred,offsetting the UITextview parameters means the text is anchored at the top, not centrally. Attaching menus to a UILabel seems very difficult.


回答1:


MyViewController.h

@interface MyViewController : UIViewController

// Linked textField from interface builder
@property (weak, nonatomic) IBOutlet UITextField *textField;

@end

MyViewController.m

In viewDidLoad method, add wiki button to UIMenuController.

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Add wiki button to UIMenuController
    UIMenuController *menuController = [UIMenuController sharedMenuController];
    UIMenuItem *wikiItem = [[UIMenuItem alloc] initWithTitle:@"Wiki" action:@selector(openWiki:)];
    [menuController setMenuItems:[NSArray arrayWithObject:wikiItem]];

}

Create openWiki method:

- (void)openWiki:(id)sender {

    if(![[_textField selectedTextRange] isEmpty]) {

        // Url string
        NSString *urlStr = [NSString stringWithFormat:@"http://en.wikipedia.org/wiki/%@",[_textField textInRange:[_textField selectedTextRange]]];

        // Create url object
        NSURL *myURL = [[NSURL alloc] initWithString:urlStr];

        // Open url in safari
        [[UIApplication sharedApplication] openURL:myURL];

    }
}

And that's it.



来源:https://stackoverflow.com/questions/19976470/how-to-add-custom-menu-item-to-uitextview-menu-which-is-a-link-to-the-wikipedia

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!