Sag*_*ari 20 iphone xcode objective-c uiwebview uimenucontroller
当用户在UIWebView上完成选择时,我想显示2个选项,如"hi"和"bye".
我已将观察者添加到我的视图控制器,如下所示.但我不知道进一步的实施.
[[UIMenuController sharedMenuController] addObserver:self
forKeyPath:UIMenuControllerWillShowMenuNotification
options:nil
context:nil
];
Run Code Online (Sandbox Code Playgroud)
Jac*_*ues 44
萨格尔,
你的问题已经有几个月了,但我终于想到了这个,所以我想我会回答它,以防它帮助别人.
我将以下代码添加到包含webview的视图控制器的viewDidAppear:方法中.
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
UIMenuItem *customMenuItem1 = [[[UIMenuItem alloc] initWithTitle:@"Custom 1" action:@selector(customAction1:)] autorelease];
UIMenuItem *customMenuItem2 = [[[UIMenuItem alloc] initWithTitle:@"Custom 2" action:@selector(customAction2:)] autorelease];
[[UIMenuController sharedMenuController] setMenuItems:[NSArray arrayWithObjects:customMenuItem1, customMenuItem2, nil]];
}
Run Code Online (Sandbox Code Playgroud)
在我的viewDidDisappear:中,我继续删除这些项目:
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[[UIMenuController sharedMenuController] setMenuItems:nil];
}
Run Code Online (Sandbox Code Playgroud)
然后,我在视图控制器中实现了canPerformAction:withSender:方法.它有助于理解响应者和响应者链的概念,以了解这里发生了什么.基本上,你的uiviewcontroller是响应者链的一部分,所以它会被问到它是否可以处理响应者链上方的对象(如UIWebView)不知道如何处理的任何操作(比如上面添加的自定义操作)有关详细信息,请参阅UIResponder文档和iOS事件处理指南.
现在,当为webview调用canPerformAction:withSender:时,sender参数设置为nil.所以,我试着对我如何写这个函数有点聪明.基本上,我确保发件人是零,我向用户显示webview,页面上的任何其他控件都不是第一个响应者.如果是这种情况,那么我检查这是否是我在上面定义的操作之一,如果是,则返回YES.在所有其他情况下,我通过在super上调用相同的方法从UIViewController返回默认值.
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
if (webView.superview != nil && ![urlTextField isFirstResponder]) {
if (action == @selector(customAction1:) || action == @selector(customAction2:)) {
return YES;
}
}
return [super canPerformAction:action withSender:sender];
}
Run Code Online (Sandbox Code Playgroud)
当然,现在下一步是弄清楚如何实际选择(可能是通过在webview中运行一些JavaScript).
小智 5
迅速:
class ViewController: UIViewController {
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// add two custom menu items to the context menu of UIWebView (assuming in contenteditable mode)
let menuItem1 = UIMenuItem(title: "Foo", action: #selector(ViewController.foo))
let menuItem2 = UIMenuItem(title: "Bar", action: #selector(ViewController.bar))
UIMenuController.sharedMenuController().menuItems = [menuItem1, menuItem2]
}
override func viewDidDisappear(animated: Bool) {
super.viewDidAppear(animated)
UIMenuController.sharedMenuController().menuItems = nil
}
override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
if webView?.superview != nil {
if action == #selector(ViewController.foo) || action == #selector(ViewController.bar) {
return true
}
}
return super.canPerformAction(action, withSender: sender)
}
func foo() {
print("foo")
}
func bar() {
print("bar")
}
}
Run Code Online (Sandbox Code Playgroud)
注意:#selector 在 Swift 2.2 中可用。