按钮点击后从上一个视图更改图像(Swift)

时间:2016-10-17 19:41:28

标签: ios swift

点击一个按钮后,我想在我之前的View中看到我的UIImageView中的图像。

有任何帮助吗?谢谢。

MainViewController.swift

class MainViewController: UIViewController {

    @IBOutlet weak var hatBackground: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        hatBackground.image = UIImage(named: "black-hat-front.jpg")
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showPatches"{
            if let childViewController = segue.destination as? ChildViewController{

            }
        }
    }
}

ChildViewController.swift

class ChildViewController: UIViewController {

    @IBOutlet weak var doubleCupButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "Choose a Patch"
    }

    @IBAction func doubleCupButtonPressed(_ sender: AnyObject) {
        hatBackground.image = UIImage(named: "badgal-hat.jpg")??

        // Go back to previous Controller
        navigationController?.popViewController(animated: true)
    }

}

1 个答案:

答案 0 :(得分:0)

如果我很好理解,你想在ChildViewController中选择图像并在MainViewController中显示它。要做到这一点,你应该实现这样的委托模式:

MainViewController

class MainViewController: UIViewController, ChildViewControllerDelegate {
  @IBOutlet weak var hatBackground: UIImageView!

  override func viewDidLoad() {
    super.viewDidLoad()
    hatBackground.image = UIImage(named: "black-hat-front.jpg")
  }

  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showPatches"{
      if let childViewController = segue.destination as? ChildViewController{
        childViewController.delegate = self
      }
    }
  }

  func didSelectImage(image: UIImage?) {
    self.hatBackground.image = image
  }
}

ChildViewController

class ChildViewController: UIViewController {

  @IBOutlet weak var doubleCupButton: UIButton!
  var delegate: ChildViewControllerDelegate?

  override func viewDidLoad() {
    super.viewDidLoad()
    self.title = "Choose a Patch"
  }

  @IBAction func doubleCupButtonPressed(_ sender: AnyObject) {
    let selectedImage = UIImage(named: "badgal-hat.jpg")
    delegate?.didSelectImage(image: selectedImage)
    self.navigationController?.popViewController(animated: true)
  }
}

ChildViewControllerDelegate

protocol ChildViewControllerDelegate {
  func didSelectImage(image:UIImage?)
}