简体   繁体   English

长UIButton标题标签在中心而不是在右侧截断

[英]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 . 使用Swift 5和iOS 12.3, UILabel有一个名为lineBreakMode的属性。 lineBreakMode has the following declaration: lineBreakMode具有以下声明:

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: 下面的Playground代码显示了如何使用NSLineBreakMode.byTruncatingTail值设置lineBreakMode以截断右侧的UIButton的标题标签:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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