我想使用2个按钮在同一ViewController上显示两个图像

时间:2019-01-04 04:15:39

标签: ios swift

我想使用2个按钮在同一ViewController上显示两个图像。我该怎么办?

import Foundation
import UIKit

class GetImagesViewController: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    let imagePicker = UIImagePickerController()

    @IBOutlet weak var imageView1: UIImageView!
    @IBOutlet weak var imageView2: UIImageView!

    @IBAction func selectSignature1(_ sender: Any) {
        openPhotoLibraryForSelectSignature()
    }

    @IBAction func selectPhoto(_sender: Any){
        openPhotoLibraryForSelectPhoto()
    }

    func openPhotoLibraryForSelectSignature() {
        guard UIImagePickerController.isSourceTypeAvailable(.photoLibrary) else {
            print("can't open photo library")
            return
        }

        imagePicker.sourceType = .photoLibrary
        imagePicker.delegate = self

        present(imagePicker, animated: true)
    }

    func openPhotoLibraryForSelectPhoto() {
        guard UIImagePickerController.isSourceTypeAvailable(.photoLibrary) else {
            print("can't open photo library")
            return
        }

        imagePicker.sourceType = .photoLibrary
        imagePicker.delegate = self

        present(imagePicker, animated: true)
    }

    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        dismiss(animated: true, completion: nil)
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        let image = info [UIImagePickerController.InfoKey.originalImage] as? UIImage

        self.dismiss(animated: true, completion: nil)
        imageView1.image = image
    }
}

1 个答案:

答案 0 :(得分:2)

您可以创建一个名为focus的变量,该变量指向您将要更改的UIImageView。用户选择图像后,只需更新focus的图像即可。

class GetImagesViewController: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    var focus: UIImageView!

    @IBAction func selectSignature1(_ sender: Any) {
        focus = imageView1
        openPhotoLibraryForSelectSignature()

    }
    @IBAction func selectPhoto(_sender: Any){
        focus = imageView2
        openPhotoLibraryForSelectPhoto()
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        let image = info [UIImagePickerController.InfoKey.originalImage] as? UIImage

        self.dismiss(animated: true, completion: nil)
        focus.image = image
    }

    // rest of your code
}