简体   繁体   中英

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?

usernameButton.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM