Why does sizeToFit() require either width or height to be specified?
I tried it on a label, here is what I got:
Width/height not specified
nameLabel.pin.top(50).left(40).sizeToFit()
dump(nameLabel.frame)
▿ (40.0, 50.0, 0.0, 0.0)
▿ origin: (40.0, 50.0)
- x: 40.0
- y: 50.0
▿ size: (0.0, 0.0)
- width: 0.0
- height: 0.0
Added width to trigger size calculation
nameLabel.pin.top(50).height(40).left(40).sizeToFit()
dump(nameLabel.frame)
▿ (40.0, 50.0, 173.333333333333, 20.3333333333333)
▿ origin: (40.0, 50.0)
- x: 40.0
- y: 50.0
▿ size: (173.333333333333, 20.3333333333333)
- width: 173.333333333333
- height: 20.3333333333333
I tried to investigate what I was doing wrong, I found this test:
class AdjustSizeSpec: QuickSpec {
...
it("should adjust the size of aView by calling sizeToFit() method without having specified width and height") {
aView.pin.sizeToFit()
expect(aView.frame).to(equal(CGRect(x: 140.0, y: 100.0, width: 100.0, height: 60.0)))
}
...
}
aView.pin.sizeToFit()
- this code can be commented out, the test still passes
There a condition in this file: PinLayoutImpl.swift, line 966
if shouldSizeToFit && (newWidth != nil || newHeight != nil) {
// ... calculate size
}
(newWidth != nil || newHeight != nil)
- this condition requires either width or height to specified in order to sizeThatFits
to be invoked.
I commented out this condition and my code nameLabel.pin.top(50).left(40).sizeToFit()
produces the correct size.
I guess, there should be some reason for the condition to be in the code :).
Can it potentially be disabled for certain UIView subtypes like UILabel?