Skip to content

Instantly share code, notes, and snippets.

@appsandwich
Created October 16, 2018 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save appsandwich/3803b1b072c0b68666e5c5947ecaf182 to your computer and use it in GitHub Desktop.
Save appsandwich/3803b1b072c0b68666e5c5947ecaf182 to your computer and use it in GitHub Desktop.
import UIKit
extension UIView {
func traverseResponderChainForUIViewController() -> UIViewController? {
guard let nextResponder = self.next else {
return nil
}
if nextResponder is UIViewController {
return nextResponder as? UIViewController
}
else if nextResponder is UIView {
return (nextResponder as? UIView)?.traverseResponderChainForUIViewController()
}
else {
return nil
}
}
func viewController() -> UIViewController? {
return self.traverseResponderChainForUIViewController()
}
var key: String {
guard let vc = self.viewController() else {
return ""
}
var numIvars: UInt32 = 0
guard let ivars = class_copyIvarList(type(of: vc), &numIvars) else {
return ""
}
var k = ""
for i in 0..<numIvars {
let index = Int(i)
let ivar = ivars[index]
if self == object_getIvar(vc, ivar) as? UIView, let ivarName = String.init(utf8String: ivar_getName(ivar)!) {
k = ivarName
break
}
}
free(ivars)
return k
}
}
class ViewController: UIViewController {
let testView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.addSubview(testView)
DispatchQueue.main.async {
print("key: \(self.testView.key)")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment