Search code examples
iosswiftuikituilabel

Why UILabel giving extra padding in swift?


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 "-"


Solution

  • 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),
    ])