我正在测试以下代码:
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);
最终结果在标签的中心截断和省略。我最后想要它,但我必须为此设置什么属性?
答案 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()