Skip to content

Instantly share code, notes, and snippets.

@algal
Created November 19, 2017 02:46
Show Gist options
  • Save algal/56dfc557dec5ceeb5c31b66a57467d70 to your computer and use it in GitHub Desktop.
Save algal/56dfc557dec5ceeb5c31b66a57467d70 to your computer and use it in GitHub Desktop.
/*:
Paste this into Swift Playgrounds on an iPad to see how
modifying a label's frame affects its intrinsicContentSize.
As near as I can tell, frame currently does not affect
intrinsicContentSize.
At least I am sure it did not used to affect it.
*/
import UIKit
import PlaygroundSupport
class ViewController : UIViewController
{
let v = UIView(frame: .zero)
let label = UILabel(frame: .zero)
let button1 = UIButton(type: UIButtonType.custom)
let but2 = UIButton(type: .custom)
override func loadView() {
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .green
self.view = v
setupLabel()
setupButton()
}
func setupLabel() {
label.text = repeatElement("Hello world. ", count: 1).joined(separator: "")
label.backgroundColor = .white
v.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
label.centerXAnchor.constraint(equalTo: label.superview!.centerXAnchor).isActive = true
label.centerYAnchor.constraint(equalTo: label.superview!.centerYAnchor).isActive = true
}
func setupButton() {
button1.setTitle("log (lastLog= none)", for: .normal)
button1.addTarget(self, action: #selector(logICS), for: .touchUpInside)
but2.setTitle("set frame", for: .normal)
but2.addTarget(self, action: #selector(expandFrame), for: .touchUpInside)
let sv = UIStackView(arrangedSubviews: [but2,button1])
sv.axis = UILayoutConstraintAxis.horizontal
sv.distribution = UIStackViewDistribution.fillProportionally
v.addSubview(sv)
sv.translatesAutoresizingMaskIntoConstraints=false
sv.centerXAnchor.constraint(equalTo: sv.superview!.centerXAnchor).isActive = true
sv.widthAnchor.constraint(equalTo: sv.superview!.widthAnchor).isActive = true
sv.bottomAnchor.constraint(equalTo: sv.superview!.bottomAnchor).isActive = true
}
@objc
func logICS() {
let s = "log (lastLog= ics: \(label.intrinsicContentSize);\n\tframe: \(label.frame))"
self.button1.titleLabel?.numberOfLines = 2
self.button1.setTitle(s, for: .normal)
print(label.intrinsicContentSize)
print(label.frame)
}
@objc
func expandFrame() {
self.label.frame = self.label.frame.insetBy(dx: -50, dy: 0)
}
@objc
func shrinkFrameToFitSuperview() {
label.frame = label.frame.intersection(label.superview!.bounds)
}
}
PlaygroundPage.current.liveView = ViewController()
PlaygroundPage.current.needsIndefiniteExecution = true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment