Why UILabel giving extra padding in swift?

83 Views Asked by At

I am using UILabels in UITableViewCell My code is below, I don't know why it gives the padding ?

  cell.lbl1.text = "Name            - " 
  cell.lbl2.text = "Class           - " 
  cell.lbl3.text = "Reason          - " 

enter image description here

I am looking for consistent spacing from text before "-"

2

There are 2 best solutions below

0
Sweeper On BEST ANSWER

You are assuming each character is equally wide. That is only true for monospace fonts. You can get the default monospaced font by using UIFont.monospacedSystemFont:

cell.lbl1.font = UIFont.monospacedSystemFont(ofSize: UIFont.systemFontSize, weight: .regular)

If you don't want to change the font, a simple solution would be to put the "-" character into another UILabel. This way, you can constraint all the labels on the left to have the same width, and that the "-" labels would be on the right of them.

An example of doing this with UIStackViews:

func makeLabel(_ text: String) -> UILabel {
    let label = UILabel()
    label.text = text
    label.font = UIFont.monospacedSystemFont(ofSize: UIFont.systemFontSize, weight: .regular)
    return label
}

func makeHStack(_ text: String) -> UIStackView {
    let stackView = UIStackView(arrangedSubviews: [makeLabel(text), makeLabel("-")])
    stackView.axis = .horizontal
    NSLayoutConstraint.activate([
        // freely adjust this 0.4 ratio
        stackView.arrangedSubviews[0].widthAnchor.constraint(equalTo: stackView.widthAnchor, multiplier: 0.4)
        // making the width equal to a constant is also an option
    ])
    return stackView
}

// constructing the 3 rows and placing them into a superview
let vstack = UIStackView(arrangedSubviews: [makeHStack("Name"), makeHStack("Class"), makeHStack("Reason")])
vstack.axis = .vertical

view.addSubview(vstack)
vstack.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
    vstack.widthAnchor.constraint(equalTo: view.widthAnchor),
    vstack.centerXAnchor.constraint(equalTo: view.centerXAnchor),
    vstack.centerYAnchor.constraint(equalTo: view.centerYAnchor),
])
0
HangarRash On

There's a simple solution - replace the spaces with tabs. No need for monospaced fonts or stack views.

Start with:

cell.lbl1.text = "Name\t\t\t- " 
cell.lbl2.text = "Class\t\t\t- " 
cell.lbl3.text = "Reason\t\t\t- "

This should line up the hyphens. Depending on the font you might need more or less \t (tab) characters in a given label than the others to get it to line up.