我有一个配置文件类和设置类
profile类包含一个内部函数
class Profile: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
internal func profileSelectFromGallery(sender: Profile){
let myPickerController = UIImagePickerController()
myPickerController.delegate = sender;
myPickerController.sourceType =
UIImagePickerControllerSourceType.PhotoLibrary
sender.presentViewController(myPickerController, animated:true, completion: nil)
}
}
Run Code Online (Sandbox Code Playgroud)
我想在设置类中使用profileSelectFromGallery,我在下面有两次尝试
class SettingsVC: UITableViewController {
// I will call this private function on a click events
private func selectFromGallery(){
// let profile = Profile()
// profile.profileSelectFromGallery(self)
Profile.profileSelectFromGallery(self)
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码结果Cannot convert value of type 'SettingsVC' to expected argument type 'Profile'因为profileSelectFromGallery需要一个类的参数Profile所以我想要做的是更改发送者,以便我可以从我的任何一个类而不仅仅是我的Profile类中使用它.
所以问题是你无法将a转换SettingsVC成a Profile.如果您查看方法签名,您会看到它期望Profile:
internal func profileSelectFromGallery(sender: Profile)
您正在尝试传入SettingVC selectFromGallery()
在里面,profileSelectFromGallery你希望发件人既是a UIViewController又是a UIImagePickerControllerDelegate.有几种方法可以做到这一点:
最简单的是更改方法签名.你会做这样的事情:
internal func profileSelectFromGallery(sender: UIImagePickerControllerDelegate){
guard let vc = sender as? UIViewController else {
return
}
let myPickerController = UIImagePickerController()
myPickerController.delegate = sender;
myPickerController.sourceType =
UIImagePickerControllerSourceType.PhotoLibrary
vc.presentViewController(myPickerController, animated:true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)
这里有两个主要内容:sender更改为正确的委托方法,并将guard语句转换为VC以进行presentViewController调用.
更棒的方法是使用协议扩展!
extension UIImagePickerControllerDelegate where Self: UIViewController, Self: UINavigationControllerDelegate {
func profileSelectFromGallery() {
let myPickerController = UIImagePickerController()
myPickerController.delegate = self
myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(myPickerController, animated:true, completion: nil)
}
}
Run Code Online (Sandbox Code Playgroud)
基本上我在这里做的是为每个人添加一个方法UIImagePickerControllerDelegate也是一个UIViewController和一个UINAvigationControllerDelegate.这意味着我可以在Profile和SettingVC上调用它(一旦你将必要的委托添加到SettingVC).你需要做的就是:
let profile = Profile()
profile.profileSelectFromGallery()
let settingVC = SettingVC()
settingVC.profileSelectFromGallery()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
217 次 |
| 最近记录: |