几天来我一直在尝试让 UISplitViewController
调用委托(delegate)。我尝试在 MasterViewController
中设置它,我尝试在 DetailViewController
中设置它,我尝试将 SVC
作为容器中的嵌入式 View Controller 在另一个 View Controller 中,并使用 prepareForSegue
调用来设置委托(delegate)。我尝试从 AppDelegate
中的 Storyboard 实例化它并在那里设置委托(delegate)。永远不会调用委托(delegate)。我要疯了。
我在 iOS 10.3.1 上使用最新的非测试版 Swift (3.1)。
我已经使用调试器来检查委托(delegate)是否确实已设置并保留在内存中,但是,这些方法从未被调用。
非常感谢您能为我提供的任何帮助。
这是我当前的 AppDelegate,但我已经尝试了无数方法,正如我所说:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
Realm.Configuration.defaultConfiguration.deleteRealmIfMigrationNeeded = true
if let svc = self.window?.rootViewController as? UISplitViewController {
svc.delegate = svc.viewControllers.last as! UISplitViewControllerDelegate
}
return true
}
编辑 1:
有些人不明白我要实现的委托(delegate)是什么。澄清一下,我试图控制 UISplitViewController
的委托(delegate),换句话说,就是 UISplitViewControllerDelegate
。我尝试这样做的原因是能够控制 View 的折叠。在 UISplitViewController
的默认配置中,在纵向模式的 iPhone 上,它默认为 detailViewController
。对于大多数应用程序(和我的应用程序)来说,这种行为显然是错误的。我打算首先显示列出我要显示的内容的 masterViewController
,然后仅在选择项目时触发 detailViewController
。
我也会接受一个答案,它给了我一些替代方法来实现这种行为(除非我的 detailViewController
设置了内容,否则最好在纵向上使用 masterViewController
。
我知道您可以通过不在 Storyboard 中设置 detailViewController
并在选择项目时使用 showDetail
segue 来获得所描述的行为,但我的问题是当没有选择任何项目时,我无法使用默认 View ,导致在 iPad 或 iPhone Plus 上横向显示灰色方 block (不是很漂亮)。
最佳答案
请尝试下面的代码,它适合我。
在 AppDelegate 中:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navViewController = splitViewController.viewControllers.first as? UINavigationController
let masterVC = navViewController?.topViewController as? MasterViewController
let detailViewController = splitViewController.viewControllers.last as? DetailsViewController
masterVC?.delegate = detailViewController
return true
}
在 MasterViewController 中
protocol MasterViewControllerDelegate : class{
func passingData(strName : String)
}
class MasterViewController: UITableViewController {
weak var delegate : MasterViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
//Calling Delegate
delegate?.passingData(strName: "Any Message")
if let detailViewController = self.delegate as? DetailsViewController {
splitViewController?.showDetailViewController(detailViewController, sender: nil)
}
}
}
在DetailViewController中
class DetailsViewController: UIViewController, MasterViewControllerDelegate{
//Other IBOutlet and Methods
//Delegate method of MasterViewControllerDelegate
func passingData(strName : String)
print(strName) //OUTPUT: "Any Message"
}
}
我希望它也对你有用。
关于ios - UISplitViewController 委托(delegate)从未调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44512705/