我有一個DetailViewController,它是在應用程序啓動開始時尚未推送的子菜單的代理。在這裏,我想知道哪裏是將委託屬性分配給ViewController的最佳位置。如何在UISplitViewController中分配MasterViewController子菜單的代理
這是我所做的AppDelegates.swift
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
dataController = DataController()
let splitViewController = self.window!.rootViewController as! UISplitViewController
splitViewController.delegate = self
let detailNavigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
detailNavigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
let mainVC = detailNavigationController.topViewController as! MainViewController
mainVC.dataController = dataController
let masterNavigationController = splitViewController.viewControllers[0] as! UINavigationController
let mainMenuVC = masterNavigationController.topViewController as! MainMenuViewController
mainMenuVC.dataController = dataController
self.storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
let nationsMenuVC = storyboard.instantiateViewControllerWithIdentifier("NationsMenuViewController") as! NationsMenuViewController
nationsMenuVC.delegate = mainVC
return true
}
和子菜單(NationsMenuVC)具有這樣的:
protocol NationsMenuViewControllerDelegate: class {
func nationSelected(nation: City?)
}
class NationsMenuViewController: UITableViewController {
var nations:[City] = []
var moc: NSManagedObjectContext!
weak var delegate: NationsMenuViewControllerDelegate?
override func viewDidLoad() {
.
.
.
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectedCity = self.nations[indexPath.row]
self.delegate?.nationSelected(selectedCity)
print("clicked at \(selectedCity.name)")
}
}
而且我也實現我的詳細視圖 - 控制委託協議(MainVC ),但功能沒有觸發。我想知道是否因爲委託屬性在應用啓動時被分配爲弱,並且因爲它還沒有從主菜單中進行任何引用(因爲用戶還沒有實際在主視圖控制器級別單擊它),委託鏈接可能已經被解除了記憶?
在這種情況下,哪裏可以宣佈尚未加載的viewcontroller委託的最佳位置?
extension MainViewController: NationsMenuViewControllerDelegate {
func nationSelected(nation: City?) {
if let selectedCity = nation {
let coor:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: selectedCity.latitude!.doubleValue, longitude: selectedCity.longitude!.doubleValue)
let span:MKCoordinateSpan = MKCoordinateSpan(latitudeDelta: 8.0, longitudeDelta: 8.0)
let region:MKCoordinateRegion = MKCoordinateRegion(center: coor, span: span)
self.mapView.setRegion(region, animated: true)
print("selected \(selectedCity.name)")
}
}
}
感謝Shripada,但可你只需調用self.window!出於藍色得到像這樣的UISplitViewController? 讓splitViewController = self.window!.rootViewController as! UISplitViewController – Kann
沒關係,我只是這樣做了: self.window = UIApplication.sharedApplication()。keyWindow – Kann