右侧导航按钮单击时未显示Swift菜单

时间:2017-09-22 00:06:47

标签: swift uimenucontroller

Swift的新手。我有一个简单的用户界面:在UINavigationBar的顶部放置一个UIWebView,在右边的一个按钮项目上放置一个显示菜单的操作,以允许使用选择不同的页面显示在网络视图。

显示视图控制器如下:

class ViewController: UIViewController {
    @IBOutlet weak var webView: UIWebView!
    @IBOutlet weak var menu: UIBarMenuItem!
    @IBOutlet weak var viewnav: UIView!

    override func viewDidLoad() {
        super.viewDidLoad();
        let url = URL(string:"about:blank")
        let req = URLRequest(url:url!)
        webView.loadRequest(req)
    }

    @obj func dummy(){
    }

    @IBAction func MenuShow(sender: UIBarButtonItem){
        let menu = UIMenuController.shared
        viewnav.becomeFirstResponder()
        menu.setTargetRect(viewnav.frame, in:viewnav)

        let dummy = UIMenuItem(title:"Dummy", action: #selector(dummy))

        menu.menuItems = [dummy]
        menu.setMenuVisible(true, animated: true)

        //for test only; should move to menu item actions
        let url = URL(string:"https://www.apple.com")
        let req = URLRequest(url:url!)
        webView.loadRequest(req)    
    }

}

(我已将网页视图,条形按钮连接到UI对象;对于viewnav,我尝试在Main.storyboard中添加新的虚拟视图或使用现有导航栏,两者都具有相同的结果)

生成的应用程序显示空白页面,当我点击菜单按钮时,跳转到Apple的主页,因此上面的代码按预期运行。但菜单没有显示,所以上面的代码出了什么问题?

(还有一些其他类似问题,例如this,但他们似乎没有解决问题)

1 个答案:

答案 0 :(得分:0)

answer给出了解决方案:

override var canBecomeFirstResponder: Bool {
    return true
}

并将此行添加到viewDidLoad方法

view.becomeFirstResponder()

完整版:

class ViewController: UIViewController {
    @IBOutlet weak var webView: UIWebView!
    @IBOutlet weak var menuButton: UIBarMenuItem!

    override func viewDidLoad() {
        super.viewDidLoad();
        let url = URL(string:"about:blank")
        let req = URLRequest(url:url!)
        webView.loadRequest(req)

        view.becomeFirstResponder()

        let menu = UIMenuController.shared
        let dummy = UIMenuItem(title:"Dummy", action: #selector(dummy))
        menu.menuItems = [dummy]
    }

    override var canBecomeFirstResponder: Bool {
        return true
    }

    @obj func dummy(){
        let url = URL(string:"https://www.apple.com")
        let req = URLRequest(url:url!)
        webView.loadRequest(req)    
        menu.setMenuVisible(true, animated: false)
    }

    @IBAction func MenuShow(sender: UIBarButtonItem){
        let menu = UIMenuController.shared
        let bv = menuButton.value(forKey: "view") as? UIView
        menu.setTargetRect(bv!.frame, in:view)

        menu.setMenuVisible(true, animated: true)
    }
}