Skip to content

Commit 19cd733

Browse files
author
Baris Sencan
committed
Test UIView.sizeToFit(constrainedSize)
Also changed how it works, and the arguments it can take. All for the better.
1 parent d1932b6 commit 19cd733

File tree

2 files changed

+27
-8
lines changed

2 files changed

+27
-8
lines changed

ManualLayout/UIView+ManualLayout.swift

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -101,13 +101,15 @@ public extension UIView {
101101

102102
// MARK: - Automatic Sizing
103103

104-
public func sizeToFit(constrainedSizeTuple: (CGFloat, CGFloat)) {
105-
sizeToFit(CGSize(
106-
width: constrainedSizeTuple.0,
107-
height: constrainedSizeTuple.1))
104+
public func sizeToFit(width: CGFloat, _ height: CGFloat) -> CGSize {
105+
return sizeToFit(CGSize(width: width, height: height))
108106
}
109107

110-
public func sizeToFit(constrainedSize: CGSize) {
111-
size = sizeThatFits(constrainedSize)
108+
public func sizeToFit(constrainedSize: CGSize) -> CGSize {
109+
var newSize = sizeThatFits(constrainedSize)
110+
newSize.width = min(newSize.width, constrainedSize.width)
111+
newSize.height = min(newSize.height, constrainedSize.height)
112+
size = newSize
113+
return newSize
112114
}
113-
}
115+
}

ManualLayoutTests/UIViewManualLayoutTests.swift

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -226,4 +226,21 @@ class UIViewManualLayoutTests: XCTestCase {
226226
"left2 changes without a swap should modify frame size")
227227
// TODO: Test swap behavior.
228228
}
229-
}
229+
230+
func testSizeToFit() {
231+
let containerView = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: 200))
232+
let label = UILabel(frame: CGRectZero)
233+
label.text = "lorem ipsum dolor sit amet"
234+
label.numberOfLines = 5
235+
containerView.addSubview(label)
236+
label.sizeToFit(containerView.frame.size)
237+
XCTAssert(
238+
label.frame.size.height > 20 && label.frame.size.width <= 20,
239+
"sizeToFit should size the view to fit given constrained size")
240+
label.numberOfLines = 1
241+
label.sizeToFit(containerView.frame.size)
242+
XCTAssert(
243+
label.frame.size.height > 20 && label.frame.size.width <= 20,
244+
"sizeToFit should size the view to fit given constrained size")
245+
}
246+
}

0 commit comments

Comments
 (0)