问题
could you please help me with UIImagePickerController
I have 12 ImageViews in 1 ViewController. I need help so that each ImageView could pick different photos from Library. Someone told me to use Tags for them but I can't make it work cause i'm new in Swift.
回答1:
Enable User Interaction Enabled
for each UIImageView on a Storyboard.
Add TapGestureRecogniser
to each UIImageView
. Connect each TapGestureRecogniser
with IBAction
.
@IBAction func tap(_ sender: UITapGestureRecognizer) {
currentImageView = sender.view as! UIImageView
let picker = UIImagePickerController()
picker.delegate = self
self.present(picker, animated: true, completion: nil)
}
Define variable to store current UIImageView
private var currentImageView: UIImageView? = nil
Handle image selection and assign the image to currentImageView
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let image = info[UIImagePickerController.InfoKey.originalImage]
currentImageView?.image = image as! UIImage
self.dismiss(animated: true, completion: nil)
}
回答2:
It's not about the swift. You set up a "tag" number in the Interface builder (or in the code. There is a .tag property on the UIResponder descendants). After that you make a switch in your callback method like
To make it a bit clearer:
let picker: UIImagePicker! = {
// setup your image picker here, don't forget to set the proper delegate
}()
var lastSender: AnyObject?
func onTouch(_ sender: AnyObject?) {
// add checks for the sender here
lastSender = sender
present(picker, animated: true, completion: *Your Completion*)
}
Delegate:
in
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any])
let image = *Get Image From Info*
lastSender?.image = image
来源:https://stackoverflow.com/questions/52238869/one-uiimagepickercontroller-for-multiple-imageviews