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

后端 未结 1 1308
执念已碎
执念已碎 2021-02-08 04:42

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 canno

1条回答
  •  野性不改
    2021-02-08 05:41

    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.

    0 讨论(0)
提交回复
热议问题