From 5035a097d08386e366f2046b93fd41c6fc0b6ba5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adria=CC=81n=20Barreiro=20Villalustre?= Date: Tue, 9 Jul 2019 15:24:47 +0200 Subject: [PATCH] Add observer to rotation events When a rotation occurs call updateLayout --- UIImageViewAligned.swift | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/UIImageViewAligned.swift b/UIImageViewAligned.swift index 3df8c92..0f8ec87 100644 --- a/UIImageViewAligned.swift +++ b/UIImageViewAligned.swift @@ -209,6 +209,7 @@ open class UIImageViewAligned: UIImageView { } private func setup(image: UIImage? = nil, highlightedImage: UIImage? = nil) { + addRotationObserver() realImageView = UIImageView(image: image ?? super.image, highlightedImage: highlightedImage ?? super.highlightedImage) realImageView?.frame = bounds realImageView?.autoresizingMask = [.flexibleWidth, .flexibleHeight] @@ -216,7 +217,11 @@ open class UIImageViewAligned: UIImageView { addSubview(realImageView!) } - private func updateLayout() { + deinit { + NotificationCenter.default.removeObserver(self) + } + + @objc public func updateLayout() { let realSize = realContentSize var realFrame = CGRect(origin: CGPoint(x: (bounds.size.width - realSize.width) / 2.0, y: (bounds.size.height - realSize.height) / 2.0), @@ -254,4 +259,9 @@ open class UIImageViewAligned: UIImageView { private func getInspectableProperty(_ alignment: UIImageViewAlignmentMask) -> Bool { return self.alignment.contains(alignment) } + + private func addRotationObserver() { + UIDevice.current.beginGeneratingDeviceOrientationNotifications() + NotificationCenter.default.addObserver(self, selector: #selector(updateLayout), name: UIDevice.orientationDidChangeNotification, object: nil) + } }