UISplitViewController中的自定义UIBarButtonItem不响应点击(iPhone)

时间:2015-02-08 20:02:26

标签: ios iphone swift ios8 uisplitviewcontroller

我正在尝试自定义UIBarButtonItem UISplitViewController的外观,分为两个UINavigationController(详细信息和主视图),但不断碰到一堵砖墙。我首先遵循了建议here,但未能达到预期的效果。

如果我以这种方式在Detail View Controller的viewDidLoad方法中实现后退按钮:

if let svc = splitViewController {
    navigationItem.leftBarButtonItem = svc.displayModeButtonItem()
}

我得到默认的“后退”按钮,导航回主视图控制器。但是,如果我尝试使用以下代码自定义按钮:

    if let svc = splitViewController {
        let searchButton = UIBarButtonItem(
            image: UIImage(named: "magnifying-glass"),
            style: UIBarButtonItemStyle.Plain,
            target: svc.displayModeButtonItem().target,
            action: svc.displayModeButtonItem().action
        )

        navigationItem.leftBarButtonItem = searchButton
    }

我在导航栏中获得了所需的图标,但点击时它什么也没做。我在控制台中调试了动作和目标,动作是“_triggerDisplayModeAction:”,控制器是UISplitViewController的一个实例。

关于这里发生了什么的任何想法?

1 个答案:

答案 0 :(得分:1)

我建议您在主视图控制器中的prepareForSeque中创建和使用自定义UIBarButtonItem。默认情况下,拆分视图控制器将创建详细视图控制器的新实例!忽略iPhone ios7support的部分,这是另一个故事:-) https://github.com/op183/MasterDetailDemo

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "showDetail" {
        if let indexPath = self.tableView.indexPathForSelectedRow() {
            let object = objects[indexPath.row] as String
            if let navController = (segue.destinationViewController as? UINavigationController) {
                let controller = navController.topViewController as DetailViewController
                controller.detailItem = object
                let defaultBarButton = splitViewController?.displayModeButtonItem()
                let searchButton = UIBarButtonItem(
                    image: UIImage(named: "magnifying-glass"),
                    style: UIBarButtonItemStyle.Plain,
                    target: defaultBarButton.target,
                    action: defaultBarButton.action
                )
                controller.navigationItem.leftBarButtonItem = searchButton
                controller.navigationItem.leftItemsSupplementBackButton = true
            } else {

                // iPhone ios7support
                (segue.destinationViewController as DetailViewController).detailItem = object
            }
        }
    }
}