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

时间:2014-12-02 07:50:51

标签: ios objective-c uibutton nsstring ios8

我正在测试以下代码:

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

最终结果在标签的中心截断和省略。我最后想要它,但我必须为此设置什么属性?

2 个答案:

答案 0 :(得分:5)

usernameButton.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;

答案 1 :(得分:0)

在Swift 4.1和iOS 11中,UILabel具有一个名为lineBreakMode的属性。 lineBreakMode具有以下declaration

var lineBreakMode: NSLineBreakMode { get set }
  

用于包裹和截断标签文本的技术。


下面的Playground代码显示了如何使用lineBreakMode值设置NSLineBreakMode.byTruncatingTail以便在右边截断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()