Created
November 28, 2019 06:05
-
-
Save hanawat/411cca941ee58b43cad381fedb9f8260 to your computer and use it in GitHub Desktop.
Swizzlie a process to warn of breaking autolayout.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
extension UIView { | |
/// Swizzlie a process to warn of breaking autolayout. | |
static func swizzleBreakedLayoutWarning() { | |
let anyClass: AnyClass = UIView.self | |
let originalSelector = Selector(("engine:willBreakConstraint:dueToMutuallyExclusiveConstraints:")) | |
let swizzledSelector = #selector(swizzledEngine(_:willBreak:dueTo:)) | |
guard let originalMethod = class_getInstanceMethod(anyClass, originalSelector), | |
let swizzledMethod = class_getInstanceMethod(anyClass, swizzledSelector) else { return } | |
method_exchangeImplementations(originalMethod, swizzledMethod) | |
} | |
/// Swizzled the autolayout engin method. | |
/// | |
/// - Parameters: | |
/// - engine: NSISEngine (Private Class) | |
/// - constraint: NSLayoutConstraint | |
/// - mutuallyExclusiveConstraints: [NSLayoutConstraint] | |
@objc private func swizzledEngine( | |
_ engine: Any, | |
willBreak constraint: NSLayoutConstraint, | |
dueTo mutuallyExclusiveConstraints: [NSLayoutConstraint]) { | |
NSLog("Breaked Constraint: %@", constraint) | |
if let view = constraint.firstItem as? UIView { | |
addWarningLayer(to: view) | |
} | |
if let view = constraint.secondItem as? UIView { | |
addWarningLayer(to: view) | |
} | |
} | |
/// Adds warning red layer to view's sub layer. | |
/// | |
/// - Parameter view: Warned View | |
private func addWarningLayer(to view: UIView) { | |
let layer = CALayer() | |
layer.frame = CGRect(origin: .zero, size: view.frame.size) | |
layer.backgroundColor = UIColor.red.withAlphaComponent(0.1).cgColor | |
view.layer.addSublayer(layer) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment