Ios 我想用两个按钮选择图像,并想在swift中的两个不同图像视图上显示这些图像。我该怎么做。?
我想使用两个按钮选择图像,并想在swift中的两个不同图像视图上显示这些图像Ios 我想用两个按钮选择图像,并想在swift中的两个不同图像视图上显示这些图像。我该怎么做。?,ios,swift,uiimagepickercontroller,Ios,Swift,Uiimagepickercontroller,我想使用两个按钮选择图像,并想在swift中的两个不同图像视图上显示这些图像 func pickimage(){ if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){ let controller = UIImagePickerController() controller.delegate = self
func pickimage(){
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
let controller = UIImagePickerController()
controller.delegate = self
controller.sourceType = .photoLibrary
controller.allowsEditing = false
present(controller, animated: true, completion: nil)
}
}
图像选择器代理
extension AdnewDOC : UIImagePickerControllerDelegate,UINavigationControllerDelegate {
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
frontview.image = image
frontview.contentMode = .scaleAspectFill
dismiss(animated: true, completion: nil)
}
}
您可以像这样使用
objective-c
关联类型objc\u setassociated object
和objc\u getassociated object
我已经更新了您的方法,请通过按钮操作方法传递您的图像视图obejct(您要显示图像的图像视图)。与按钮的演示动作方法类似:
import ObjectiveC
var myKey = "myObjectKey"
@IBAction func firstButtonAction(_ sender: Any) {
pickimage(imageView: firstImageView)
}
@IBAction func secondButtonAction(_ sender: Any) {
pickimage(imageView: secondImageView)
}
func pickimage(imageView: UIImageView){
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
let controller = UIImagePickerController()
objc_setAssociatedObject(controller, &myKey, imageView, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
controller.delegate = self
controller.sourceType = .photoLibrary
controller.allowsEditing = false
present(controller, animated: true, completion: nil)
}
}
并在委托方法中获取图像对象,如下所示:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let imageView = objc_getAssociatedObject(picker, &myKey) as! UIImageView
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
imageView.image = image
imageView.contentMode = .scaleAspectFill
dismiss(animated: true, completion: nil)
}
有关如何使用objc_setAssociatedObject
和objc_getAssociatedObject
的更多了解,请查看以下链接:
不明白。我想实现当我点击按钮1时,所选图像将应用于imageview1..当我点击按钮2时,所选图像将应用于imageview2。我已更新了我的答案,从按钮操作方法,您必须调用pickimage方法,这样它才能工作。您可以使用此多按钮操作方法。在这种方法中,我们将图像视图与picker控制器相关联,当图像进入委托方法时,我们将获得关联对象,即图像视图。