私はこのようにこの問題を解決:
protocol ScanningMessageViewProtocol: class {
func showMessage(_ message: String, animated: Bool)
func showMessage(_ message: String, autoHideAfterDelay time: TimeInterval?, animated: Bool)
func hideMessage(animated: Bool)
}
extension ScanningMessageViewProtocol where Self: UIView {}
protocol CLScanBarcodeViewControllerDelegate: class {
func messageViewForScanController(_ controller: CLScanBarcodeViewController) -> ScanningMessageViewProtocol
}
extension CLScanBarcodeViewControllerDelegate where Self: UIViewController {
func messageViewForScanController(_ controller: CLScanBarcodeViewController?) -> ScanningMessageViewProtocol? { return nil }
}
使用このように:
if let messageView = self.delegate?.messageViewForScanController(self) {
if messageView is UIView {
self.view.addSubview(messageView as! UIView)
(messageView as! UIView).translatesAutoresizingMaskIntoConstraints = false
let size: CGSize = self.view.bounds.size
let cropSize: CGSize = CGSize(width: size.width * 0.7, height: size.width * 0.7)
let cropRect = CGRect(x: (size.width - cropSize.width)/2.0,
y: (size.height - cropSize.height)/2.0 - distanceToCenterY,
width: cropSize.width,
height: cropSize.height)
self.view.addConstraint(NSLayoutConstraint(item: messageView, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: 20))
self.view.addConstraint(NSLayoutConstraint(item: messageView, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1, constant: -20))
self.view.addConstraint(NSLayoutConstraint(item: messageView, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: cropRect.minY + cropRect.height + 30))
self.view.addConstraint(NSLayoutConstraint(item: messageView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0, constant: 30))
messageView.showMessage("this is message", animated: true)
}
}
それは非常にエレガントな方法ではないかもしれない、誰かが間違いを訂正できることを願っています。
現在ではありませんが、将来のバージョンでは可能です(https://github.com/apple/swift-evolution/blob/master/proposals/0156-subclass-existentials.md)。 – Hamish