动态调整给定UIButton帧中2个字符串的长度

时间:2015-01-19 03:10:26

标签: ios objective-c uibutton nsstring

有2个字符串由形成UIButton标题的空格分隔。按钮框架无法更改。设备仅限iPhone肖像。如何根据要求动态控制2个字符串的长度?

要求 -

第二个字符串的最小长度为9个字符,将始终显示。 如果第一个字符串的长度大于15个字符,则可以从右侧截断,以省略号结束(...)

考虑到所有组合,我不想使用if-else对代码进行硬编码。寻找一种动态设置比率或设置字符串的方法 - 以便至少满足最低显示要求。

// Min length to be displayed is flexible based on space occupied by second string
// Input length ranges from 9 to 20+ characters.
NSString *firstString = @"FirstPartOfTheStringIsDynamic";

// Min length to be displayed 9 characters.
// Input length ranges from 9 to 18 characters.
NSString *secondString = @"123456789-Second";

if (firstString.length > 15) {
    firstString = [[firstString substringToIndex:15] stringByAppendingString:@"..."];
}

self.mainButton.titleLabel.adjustsFontSizeToFitWidth = NO;
NSString *buttonTitleString = [NSString stringWithFormat:@"%@ %@", firstString, secondString];

[self.mainButton setTitle:buttonTitleString forState:UIControlStateNormal];

尝试 |回复:https://github.com/rohanaurora/Fitting-Text

  1. 我尝试通过硬编码值计算可以适合给定UIButton的字符数,并给出第二个字符串优先级。这不是一个好习惯。
  2. 无法更改字体大小。因此,我尝试研究能够动态计算适合给定空间的字符数的解决方案。
  3. 在下面的屏幕截图中,我想截断第一个字符串并为第二个字符串腾出空间以完全显示 -

1 个答案:

答案 0 :(得分:1)

我通过计算可以容纳第一个字符串的剩余大小来解决上述难题。使用NSString类别截断省略号。

Size of First String = Size of Button - Size of Second String

// Min length to be displayed is flexible based on space occupied by second string
// Input length ranges from 9 to 20+ characters.
NSString *firstString = @"FirstPartOfTheStringIsDynamic";

// Min length to be displayed 9 characters.
NSString *secondString = @"123456789-Second";

CGSize sizeOfSecondString = [secondString sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:17.0f]}];
CGSize sizeOfButton = self.mainButton.frame.size;

// Calculate the remaining width to accomodate first string
CGFloat sizeOfFirstString = sizeOfButton.width - sizeOfSecondString.width;

firstString = [firstString stringByTruncatingToWidth:sizeOfFirstString withFont:[UIFont systemFontOfSize:17.0f]];
NSString *buttonTitleString = [NSString stringWithFormat:@"%@ %@", firstString, secondString];
self.mainButton.titleLabel.adjustsFontSizeToFitWidth = NO;

[self.mainButton setTitle:buttonTitleString forState:UIControlStateNormal];

以下是更新后的演示 - https://github.com/rohanaurora/Fitting-Text

enter image description here