首先在控制器中創建一個button
- (void)viewDidLoad {
[super viewDidLoad];
UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(20, 30, 35, 50)];
[self.view addSubview:button];
[button setTitle:@"button" forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
/*
NSLineBreakByWordWrapping = 0, // Wrap at word boundaries, default
NSLineBreakByCharWrapping, // Wrap at character boundaries
NSLineBreakByClipping, // Simply clip 裁剪從前面到后面顯示多余的直接裁剪掉
文字過長 button寬度不夠時: 省略號顯示位置...
NSLineBreakByTruncatingHead, // Truncate at head of line: "...wxyz" 前面顯示
NSLineBreakByTruncatingTail, // Truncate at tail of line: "abcd..." 后面顯示
NSLineBreakByTruncatingMiddle // Truncate middle of line: "ab...yz" 中間顯示省略號
*/
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
// you probably want to center it
button.titleLabel.textAlignment = NSTextAlignmentCenter; // if you want to
[button setTitle: @"Line1\nLine2" forState: UIControlStateNormal];
button.layer.borderColor = [UIColor blackColor].CGColor;
button.layer.borderWidth = 1.0;
}
-
此處寬度故意設置的比較小由於文字過長,則設置
button.titleLabel.lineBreakMode
的屬性為NSLineBreakByTruncatingHead
時,此時button的title顯示效果如下
-
顯示的前端省略而且只顯示了內容
line1
,line2
被省略掉,當把\n
換行符去掉時,則line2
不會被省略.
-
此處寬度故意設置的比較小由於文字過長,則設置
button.titleLabel.lineBreakMode
的屬性為NSLineBreakByTruncatingTail
時,此時button的title顯示效果如下
-
省略號在后面
-
此處寬度故意設置的比較小由於文字過長,則設置
button.titleLabel.lineBreakMode
的屬性為NSLineBreakByTruncatingMiddle
時,此時button的title顯示效果如下
-
省略號在中間
-
此處寬度故意設置的比較小由於文字過長,則設置
button.titleLabel.lineBreakMode
的屬性為NSLineBreakByClipping
時,此時button的title顯示效果如下
-
超長部分被裁剪掉
把寬度設置寬一些讓button的文字title折行顯示
- (void)viewDidLoad {
[super viewDidLoad];
UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(20, 30, 50, 50)];
[self.view addSubview:button];
[button setTitle:@"button" forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
/*
NSLineBreakByWordWrapping = 0, // Wrap at word boundaries, default
NSLineBreakByCharWrapping, // Wrap at character boundaries
NSLineBreakByClipping, // Simply clip 裁剪從前面到后面顯示多余的直接裁剪掉
文字過長 button寬度不夠時: 省略號顯示位置...
NSLineBreakByTruncatingHead, // Truncate at head of line: "...wxyz" 前面顯示
NSLineBreakByTruncatingTail, // Truncate at tail of line: "abcd..." 后面顯示
NSLineBreakByTruncatingMiddle // Truncate middle of line: "ab...yz" 中間顯示省略號
*/
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
// you probably want to center it
button.titleLabel.textAlignment = NSTextAlignmentCenter; // if you want to
[button setTitle: @"Line1\nLine2" forState: UIControlStateNormal];
button.layer.borderColor = [UIColor blackColor].CGColor;
button.layer.borderWidth = 1.0;
}
- 效果如下