Created
August 17, 2022 23:37
-
-
Save christianselig/509ba9c88a6b050ab48558ea15cb0c51 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
class ViewController: UIViewController { | |
let textViewWrapper = TextViewWrapper() | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// The problem view! I want to add this one to my set of Auto Layout constraints, | |
// even though it's not using Auto Layout internally. | |
textViewWrapper.translatesAutoresizingMaskIntoConstraints = false | |
view.addSubview(textViewWrapper) | |
// This one is well behaved. | |
let redBox = UIView() | |
redBox.backgroundColor = .systemRed | |
redBox.translatesAutoresizingMaskIntoConstraints = false | |
view.addSubview(redBox) | |
NSLayoutConstraint.activate([ | |
redBox.widthAnchor.constraint(equalToConstant: 50.0), | |
redBox.heightAnchor.constraint(equalToConstant: 50.0), | |
redBox.centerXAnchor.constraint(equalTo: view.centerXAnchor), | |
redBox.bottomAnchor.constraint(equalTo: textViewWrapper.topAnchor, constant: -50.0), | |
// Please show up 😢 | |
textViewWrapper.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor), | |
textViewWrapper.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor), | |
textViewWrapper.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor) | |
]) | |
} | |
} | |
/// A simplified version of a class that holds a text view and is laid out with frames | |
/// because Auto Layout + UITextView expanding/collapsing doesn't animate well. | |
class TextViewWrapper: UIView { | |
let textView = UITextView() | |
init() { | |
super.init(frame: .zero) | |
textView.text = "Once upon a time a turtle named Lenny went to the park to meet with his friend the tiger." | |
textView.backgroundColor = .magenta.withAlphaComponent(0.05) | |
addSubview(textView) | |
} | |
@available(*, unavailable) | |
required init?(coder aDecoder: NSCoder) { fatalError("\(#file) does not implement coder.") } | |
override func layoutSubviews() { | |
super.layoutSubviews() | |
textView.frame = bounds | |
} | |
override func sizeThatFits(_ size: CGSize) -> CGSize { | |
return CGSize(width: size.width, height: textView.sizeThatFits(size).height) | |
} | |
override func systemLayoutSizeFitting(_ targetSize: CGSize) -> CGSize { | |
return CGSize(width: targetSize.width, height: textView.sizeThatFits(targetSize).height) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
wrote this at my coffee table w/ swift playgrounds on iPad barely working so excuse the trash quality code. It IS functional..