如何将自定义菜单项添加到UITextView菜单,这是指向所选单词的维基百科页面的链接? [英] How to add custom menu item to UITextView menu, which is a link to the Wikipedia page of the selected word?
问题描述
我是Xcode的新手,我使用的是版本4.6.3 - 新版本的Macbook太旧了。
I am new to Xcode, I am using version 4.6.3 - Macbook too old for the new version.
我环顾互联网和Stack Overflow并不能找到我想要的或者我无法获得片段工作。
I looked around the internet and Stack Overflow and cannot find what I want or I cannot get snippets to work.
我想在菜单项中添加一个菜单项,这些菜单项在UITextView中长按一个单词时出现。我希望它说Wiki,当按下它时,它将链接到所选单词的维基百科页面。它可能是通过Safari或者我应该在带有webview的应用程序中执行此操作吗?
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?
我发现:
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.
不幸的是我无法理解检索wikipedia页面的建议,我不是那么高级,对不起。我通常不知道在哪里放置代码片段。
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.
UILabel我已经更好地显示了文本,矩形UITextView中的文本顶部有一个间隙,因此文本不居中,偏移UITextview参数意味着文本固定在顶部,而不是在中央。将菜单附加到UILabel似乎非常困难。
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.
推荐答案
MyViewController.h
MyViewController.h
@interface MyViewController : UIViewController
// Linked textField from interface builder
@property (weak, nonatomic) IBOutlet UITextField *textField;
@end
MyViewController.m
MyViewController.m
在 viewDidLoad
方法中,将wiki按钮添加到 UIMenuController
。
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]];
}
创建 openWiki
方法:
- (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];
}
}
就是这样。
这篇关于如何将自定义菜单项添加到UITextView菜单,这是指向所选单词的维基百科页面的链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!