Skip to content

Commit

Permalink
Adds support for text centering
Browse files Browse the repository at this point in the history
  • Loading branch information
MustiiKhalil committed Aug 24, 2022
1 parent ece857b commit 42a8bb2
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 7 deletions.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
14 changes: 7 additions & 7 deletions Sources/LCLabel/LCLabel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -238,21 +238,21 @@ final public class LCLabel: UILabel {
"The new bounds are negative with isnt allowed, check the frame or the textInsets")
textContainer.size = newBounds.size
layoutManager.ensureLayout(for: textContainer)
let calculatedValues = layoutManager.usedRect(for: textContainer)
let drawableFrame = layoutManager.usedRect(for: textContainer)
switch centeringTextAlignment {
case .center:
newBounds.origin
.y = floor((newBounds.height - calculatedValues.height) / 2)
.y = floor((newBounds.height - drawableFrame.height) / 2)
case .bottom:
newBounds.origin.y = (newBounds.height - calculatedValues.height)
newBounds.origin.y = (newBounds.height - drawableFrame.height)
case .top:
break
}
return CGRect(
x: newBounds.origin.x,
y: newBounds.origin.y,
width: calculatedValues.width,
height: calculatedValues.height)
x: newBounds.origin.x + drawableFrame.origin.x,
y: newBounds.origin.y + drawableFrame.origin.y,
width: drawableFrame.width,
height: drawableFrame.height)
}

// MARK: Private
Expand Down
23 changes: 23 additions & 0 deletions Tests/LCLabelTests/LCLabelTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,29 @@ final class LCLabelTests: XCTestCase {
XCTFail(message)
}

func testCenterTextAlignment() {
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = .center

let attStr = NSMutableAttributedString(
string: "LCLabel is a low cost label",
attributes: [
.foregroundColor: UIColor.white,
.font: UIFont.systemFont(ofSize: 14),
.paragraphStyle: paragraph,
])
let label = createLabel(
text: attStr,
frame: CGRect(x: 0, y: 0, width: 300, height: 40))
label.numberOfLines = 1
let failure = verifySnapshot(
matching: label,
as: .image,
snapshotDirectory: path)
guard let message = failure else { return }
XCTFail(message)
}

func testTextTopAlignment() {
let attStr = NSMutableAttributedString(
string: "LCLabel is a low cost label",
Expand Down

0 comments on commit 42a8bb2

Please sign in to comment.