我有一个小应用程序,可以在壁纸库中显示图像。当用户选择图像时,他们可以将图像设置为MainViewController
或返回图像库以设置不同的图像。
我的问题是:
如何在DetailsViewController
的同时将图像从MainViewController
发送到DetailsViewController
。我不希望用户转到MainViewController
。
这有什么意义吗?我已经在这几天了,无法理解如何去做。
import UIKit
class DetailViewController: UIViewController {
@IBOutlet weak var categoryImageView: UIImageView!
var image: UIImage!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBar.setBackgroundImage(UIImage(),for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true
}
override func viewDidLoad() {
super.viewDidLoad()
categoryImageView.image = image
categoryImageView.contentMode = .scaleAspectFill
}
}
答案 0 :(得分:1)
您可以使用委托。 更多信息The Swift Programming Language. Protocols
在DetailController中:
import UIKit
//define protocol
protocol DetailViewControllerDelegate {
func didSelectImage(_ image: UIImage)
}
class DetailViewController: UIViewController {
@IBOutlet weak var categoryImageView: UIImageView!
var image: UIImage!
//delegate var
var delegate: DetailViewControllerDelegate?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBar.setBackgroundImage(UIImage(),for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true
}
override func viewDidLoad() {
super.viewDidLoad()
categoryImageView.image = image
categoryImageView.contentMode = .scaleAspectFill
}
//the function that is called when you select an image in detail Controller
//or you can use collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) instead
func setImageToTheMain(_ image: UIImage) {
delegate?.didSelectImage(image)
}
}
在MainViewController中:
选项1)如果您正在使用segues
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "your segue to the detail identifier" {
let destinationController = segue.destination as? DetailViewController
//Set MainViewController as a delegate for DetailViewController
//So it will receive data from DetalVC
destinationController.delegate = self
}
}
选项2)如果您正在使用演示文稿
func goToDetail() {
let storyboard = UIStoryboard(name: "Detail storyboard name or Main", bundle: nil)
guard let detailController = storyboard.instantiateViewController(withIdentifier: "Your Detail controller identifier") as? DetailViewController else {
return
}
detailController.delegate = self
self.present(detailController, animated: true, completion: nil)
}
当您的Master设置为委托时,您需要调用在协议中创建的方法:
extension MainViewController: DetailViewControllerDelegate{
func didSelectImage(_ image: UIImage) {
//set image to the Master Controller outlet here
//something like this:
yourImageView.image = image
}
}