cdub
cdub

Reputation: 25711

A long UIButton title label truncates in the center instead of on the right

I am testing the following code:

username = @"addagkagalkjagjalggxxaklgjagjglkjag";

NSString *fullUsername = [NSString stringWithFormat:@"%@%@", @"@", username];

UIButton *usernameButton = [UIButton buttonWithType:UIButtonTypeSystem];
[usernameButton setTitle:fullUsername forState:UIControlStateNormal];

usernameButton.frame = CGRectMake(100.0, 10.0, 215.0, 25.0);

The end result truncates and ellipses in the center of the label. I want it at the end but what property do I have to set for this?

Upvotes: 3

Views: 2946

Answers (2)

Imanou Petit
Imanou Petit

Reputation: 92419

With Swift 5 and iOS 12.3, UILabel has a property called lineBreakMode. lineBreakMode has the following declaration:

var lineBreakMode: NSLineBreakMode { get set }

The technique to use for wrapping and truncating the label’s text.


The Playground code below shows how to set lineBreakMode with NSLineBreakMode.byTruncatingTail value in order to truncate a UIButton's title label on the right:

import UIKit
import PlaygroundSupport

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white

        let button = UIButton(type: .system)
        button.setTitle("Lorem ipsum dolor sit amet, consectetur adipiscing elit", for: .normal)
        button.titleLabel?.lineBreakMode = NSLineBreakMode.byTruncatingTail

        view.addSubview(button)

        button.translatesAutoresizingMaskIntoConstraints = false
        button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        button.widthAnchor.constraint(equalToConstant: 100).isActive = true
    }

}

PlaygroundPage.current.liveView = ViewController()

Upvotes: 1

Matthias Bauch
Matthias Bauch

Reputation: 90117

usernameButton.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;

Upvotes: 6

Related Questions