[swift] PopoverPresentationControllerの実装とタップした時にメインViewにタップ情報を反映させる方法
小さいウィンドウをポップアップさせるPopoverPresentationControllerの実装をやってみた。
ポップアップさせるのはCollectionViewController。
またCollectionViewControllerのセルをタップした時にメインViewにタップ情報を反映させるようにした
コードは以下の通りで、CollectionViewController上にDelegeteを作成し、メインViewにDelegateを実装させている。

メインViewController
import UIKit
class ViewController: UIViewController,UIPopoverPresentationControllerDelegate,TestCollectionViewControllerDelegate {
@IBOutlet var button:UIButton!
@IBOutlet var testImage:UIImageView!
var testViewController:TestCollectionViewController!
override func viewDidLoad() {
super.viewDidLoad()
}
//StoryBoradでButtonからTestCollectionViewControllerへSegue(ID : popup)を引いておく
override func prepare(for segue:UIStoryboardSegue,
sender:Any!) {
if let identifier = segue.identifier {
switch identifier {
case "popup":
if let contentVC = segue.destination as? TestCollectionViewController, let button = sender as? UIButton {
//set delegate
contentVC.delegate = self
//popoverPresentationController関連
let controller = contentVC.popoverPresentationController
controller?.delegate = self
//バックグラウンドの色設定(主に矢印)
controller?.backgroundColor = UIColor.gray
//矢印の方向
controller?.permittedArrowDirections = .down
//矢印が指すもの1
// controller?.sourceView = button //いらない様子
//矢印が指すもの2
controller?.sourceRect = button.bounds
//表示サイズ設定
contentVC.preferredContentSize=CGSize(width: 400, height: 200)
}
default: break
}
}
}
// iPhone用に調整するコード
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return .none
}
// Delegateを実行
func didChangeBackgroundImage(str:String) {
testImage.image = UIImage(named: "stamp_" + String(str) + ".png")
}
}
CollectionViewContorller
import UIKit
protocol TestCollectionViewControllerDelegate: class {
func didChangeBackgroundImage(str:String)
}
class TestCollectionViewController: UICollectionViewController {
@IBOutlet var myCollectionView : UICollectionView!
weak var delegate: TestCollectionViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
myCollectionView.delegate = self
myCollectionView.dataSource = self
}
//セルの個数
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 40
}
// 各セルの設定
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TestCell", for: indexPath as IndexPath)
let imageView = cell.contentView.viewWithTag(1) as! UIImageView
imageView.image = UIImage(named: "stamp_" + String(num) + ".png")
return cell
}
// セルがタップされた時の処理
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.delegate?.didChangeBackgroundImage(str: String(num))
}
}