我有一个名为UITableViewController
的{{1}}子类符合LogbookFormTVC
。在这个类中,我有一个创建并显示弹出窗口的函数:
UIPopoverPresentationControllerDelegate
我想移动此// --------------------
// LogbookFormTVC.swift
// --------------------
class LogbookFormTVC: UITableViewController, UIAdaptivePresentationControllerDelegate, UIPopoverPresentationControllerDelegate {
@IBAction func tapShowPopover(sender: AnyObject) {
//Tap to show the popover
self.presentViewController(showAircraftPicker(), animated: true, completion: nil)
}
//Build the popover
func showAircraftPicker() -> UIViewController{
//Set up modal
let storyboard = UIStoryboard(name: "Popovers", bundle: nil)
var aircraftModal = storyboard.instantiateViewControllerWithIdentifier("AircraftModal") as! AircraftPickerVC
let pc = aircraftModal.popoverPresentationController
pc?.sourceView = self.view
pc?.delegate = self
return aircraftModal
}
}
功能,并将其设置为在我的应用中的任何位置,因此我将其移至另一个文件:
showAircraftPicker()
请注意我必须将// --------------------
// SomeWhereElse.swift
// --------------------
//This works
func showAircraftPicker(controller: LogbookFormTVC) -> UIViewController{
//Set up modal
let storyboard = UIStoryboard(name: "Popovers", bundle: nil)
var aircraftModal = storyboard.instantiateViewControllerWithIdentifier("AircraftModal") as! AircraftPickerVC
let pc = aircraftModal.popoverPresentationController
pc?.sourceView = self.view
pc?.delegate = self
return aircraftModal
}
的类型设置为controller
,以便其协议符合性。但是我希望这个函数能够与任何类一起使用(当然,这符合正确的协议)。
这样做不起作用:
LogbookFormTVC
如何使这个函数适用于任何类并传递该类的协议一致性?
答案 0 :(得分:3)
您可以尝试为UIViewController创建和扩展,如下所示:
extension UIViewController {
func showAircraftPicker(delegate: UIPopoverPresentationControllerDelegate) {
let storyboard = UIStoryboard(name: "Popovers", bundle: nil)
var aircraftModal = storyboard.instantiateViewControllerWithIdentifier("AircraftModal") as! AircraftPickerVC
let pc = aircraftModal.popoverPresentationController
pc?.sourceView = self.view
pc?.delegate = delegate
return aircraftModal
}
}
答案 1 :(得分:0)
请注意我必须将控制器的类型设置为LogbookFormTVC,以便其协议符合性。但是我希望这个函数适用于任何类(当然,它符合正确的协议)。
大。因此,传递一个#"类型的对象符合正确的协议:"
func showAircraftPicker(controller: UIPopoverPresentationControllerDelegate) -> UIViewController{
这正是允许你做的协议。
如果你想同时遵守多个限制,通用就很方便了:
func showAircraftPicker<T: UIViewController
where T:UIPopoverPresentationControllerDelegate>(controller: T) -> UIViewController {