Ios 如何使用一个UIImagePickerControllerDelegate设置两个不同的图像?
我有一个“profile header”视图,有2个不同的UIImageView,还有2个UIButton-每个图像视图一个按钮。我使用协议将每个按钮的目标/选择器委托给我的控制器 在我的控制器上:Ios 如何使用一个UIImagePickerControllerDelegate设置两个不同的图像?,ios,swift,Ios,Swift,我有一个“profile header”视图,有2个不同的UIImageView,还有2个UIButton-每个图像视图一个按钮。我使用协议将每个按钮的目标/选择器委托给我的控制器 在我的控制器上: // my image picker private let profileImagePicker = UIImagePickerController() // Set's the profile image and Cover pic private var selectedProfilePic
// my image picker
private let profileImagePicker = UIImagePickerController()
// Set's the profile image and Cover pic
private var selectedProfilePic: UIImage? {
didSet {
headerView.profileImageView.image = selectedProfilePic
}
}
private var selectedCoverPic: UIImage? {
didSet {
headerView.profileCover.image = selectedCoverPic
}
}
在这个控制器上,我的视图中的每个按钮都有2个功能。一个用于我的个人资料图片按钮,另一个用于覆盖图片按钮。两者都显示图像选择器
func ChangeCoverPhoto(){
present(profileImagePicker, animated: true, completion: nil)
}
func ChangeProfilePhoto(){
present(profileImagePicker, animated: true, completion: nil)
}
然后我有了UIImagePickerControllerDelegate的扩展名
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
guard let image = info[.editedImage] as? UIImage else { return }
// ** here my Problem begin **
selectedProfilePic = image
}
如何根据按钮通过协议触发的相应功能,在selectedProfilePic或selectedCoverPic上设置来自imagepicker的选定图像?您可以为picker模式创建枚举,并在将拾取的照片分配给其相关属性时进行检查。-未知情况是可选的
private enum ImagePickerMode {
case coverPhoto
case profilePhoto
case unknown
}
通过将其作为变量保留在相关控制器上,可以检查应该更新哪个photo属性
private var imagePickerMode: ImagePickerMode = .unknown
如果您按以下方式更改更改照片的方法,则可以减少重复代码
private func changePhoto(for mode: ImagePickerMode){
imagePickerMode = mode
present(profileImagePicker, animated: true, completion: nil)
}
如果对按钮使用addTarget方法而不是iAction,则可以选择为按钮指定标记值以分隔它们
这还要求您更新ImagePickerMode以包含对应于按钮标记的RawValue。整数的默认值从0开始,增量为1。您应该更新ImagePickerMode和changePhoto,如下所示:
private enum ImagePickerMode: Int {
case coverPhoto
case profilePhoto
case unknown
}
private func changePhoto(for sender: UIButton) {
imagePickerMode = ImagePickerMode(rawValue: sender.tag) ?? .unknown
present(profileImagePicker, animated: true, completion: nil)
}
最终,委托方法变成:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
guard let image = info[.editedImage] as? UIImage else { return }
switch imagePickerMode {
// handle cases and assign related image here!
}
}
很好的解决方案,效果很好。谢谢你,安德!