Skip to content

Instantly share code, notes, and snippets.

@voznesenskym
Created August 30, 2019 00:13
Show Gist options
  • Save voznesenskym/a3f04fc3fd0d4108630c13fa01ef3fdf to your computer and use it in GitHub Desktop.
Save voznesenskym/a3f04fc3fd0d4108630c13fa01ef3fdf to your computer and use it in GitHub Desktop.
Swift playground demonstrating crash from UIView subview cycle
//: A UIKit based Playground for presenting user interface
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
override func loadView() {
let crash = true
let viewA = UIView.singleLabelNamedView("a")
let viewB = UIView.singleLabelNamedView("b")
let viewC = UIView.singleLabelNamedView("c")
let viewD = UIView.singleLabelNamedView("d")
viewA.addSubview(viewB)
viewB.addSubview(viewC)
viewC.addSubview(viewD)
if crash {
print("Should crash")
viewD.addSubview(viewA)
}
print("Did not crash...")
self.view = viewA
self.view.printViewAndSubviews()
}
}
extension UIView {
static func singleLabelNamedView(_ name : String) -> UIView {
let view = UIView()
view.backgroundColor = .white
let label = UILabel()
label.frame = CGRect(x: 150 / Int.random(in: 2...10), y: 150 / Int.random(in: 2...10), width: 200 / Int.random(in: 2...10), height: 20)
label.text = name
label.textColor = .black
view.addSubview(label)
return view
}
func printViewAndSubviews() {
print(self)
for view in subviews {
view.printViewAndSubviews()
}
}
}
PlaygroundPage.current.liveView = MyViewController()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment