Ios 将UI按钮居中';对于长度超过其宽度的单词,垂直设置标题
我想实现一个Ios 将UI按钮居中';对于长度超过其宽度的单词,垂直设置标题,ios,objective-c,uibutton,vertical-alignment,Ios,Objective C,Uibutton,Vertical Alignment,我想实现一个ui按钮,这样无论文本长度如何,标题都会居中显示 我面临的问题是按钮的宽度和字体大小必须是固定值,因为它们需要与UI的其他细节保持一致。而且我也不能截断文本 我可以拆分单词,但是仅当单词不适合标题的宽度时 目前,它适用于单行和双线文本(带空格),但当标题包含一个没有空格的长单词时,它仅将第一行居中(请参见所附图片) 我想我会做一些类似的事情: if (button.currentTitle.length > (buttonWidth/characterWidth)) { /
ui按钮
,这样无论文本长度如何,标题都会居中显示
我面临的问题是按钮的宽度和字体大小必须是固定值,因为它们需要与UI的其他细节保持一致。而且我也不能截断文本
我可以拆分单词,但是仅当单词不适合标题的宽度时
目前,它适用于单行和双线文本(带空格),但当标题包含一个没有空格的长单词时,它仅将第一行居中(请参见所附图片)
我想我会做一些类似的事情:
if (button.currentTitle.length > (buttonWidth/characterWidth)) { //2-line title buttons
// Do something special to fix the problem
}
但我尝试过设置所有这些,但没有一个成功:
[button.titleLabel setTextAlignment:NSTextAlignmentCenter];
[button.titleLabel setBaselineAdjustment:UIBaselineAdjustmentAlignCenters];
[button setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 20, 0)];
button.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
有什么想法/建议可以保持标题标签垂直居中吗?您可以将标题按字符换行,将按钮设置为
NSLineBreakByCharWrapping
(默认情况下,它在单词边界换行),只有当它包含不合适的单词时才可以。
if (button.currentTitle.length > (buttonWidth/characterWidth)) { //2-line title buttons
// Check if title contains long words
NSArray *words = [button.currentTitle componentsSeparatedByString:@" "];
for (NSString *word in words) {
if (word.length > (buttonWidth/characterWidth)) {
// Set the line break mode to char wrapping
button.titleLabel.lineBreakMode = NSLineBreakByCharWrapping;
break; // No need to continue :-)
}
}
}