Willi
Willi

Reputation: 63

How do I align the string in UIlabel?

There is a label and it's width is 100 ,there also has some string ,like 'ABC','ABCD','ABCDE'.I need the label shows the string like 'A B C','A B C D','ABCDE'.How to do for this ?

Upvotes: 0

Views: 42

Answers (1)

André Slotta
André Slotta

Reputation: 14040

You can use an NSAttributedString and the NSKernAttributeName for inter letter spacing. I created a simple subclass for your purpose:

class StretchingLabel: UILabel {

    override init(frame: CGRect) {
        super.init(frame: frame)
        sharedInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        sharedInit()
    }

    private func sharedInit() {
        self.lineBreakMode = .byClipping
        self.textAlignment = .center
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        realignText()
    }

    private var scale: CGFloat { return UIScreen.main.scale }

    override var text: String? {
        didSet {
            realignText()
        }
    }

    private func realignText() {
        guard let text = text else { return }

        let textWidth = ceil((text as NSString).boundingRect(with: self.frame.size, options: [], attributes: [NSFontAttributeName: self.font], context: nil).width * scale) / scale
        let availableWidth = self.frame.width - textWidth
        let interLetterSpacing = availableWidth / CGFloat(text.characters.count - 1)

        let attributedText = NSAttributedString(string: text, attributes: [NSFontAttributeName: self.font, NSKernAttributeName: interLetterSpacing])
        self.attributedText = attributedText
    }

}

Upvotes: 1

Related Questions