Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 286
user2963333 Avatar asked Nov 14 '13 11:11

user2963333


1 Answers

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.

like image 168
juniperi Avatar answered Oct 19 '22 20:10

juniperi