iOS:在UILabel内的句子中居中单词的算法

时间:2011-08-04 22:10:06

标签: ios algorithm uilabel

我需要通过截断UILabel内部长句的开头和结尾来将句子中的特定单词居中,例如

NSString mySentence = @"This is my very long sentence to give you an example of what I am trying to do.. And its still going..";

NSString myWord = @"example";

<Algorithm goes here>

应显示:

“...给你一个示例我想要的内容......”

如果单词更接近一端或另一端,只需尽力居中并显示适当数量的文本,例如:

NSString myWord = @"my";

“这是我的非常长的句子给你一个例子......”

有什么想法吗?

感谢。

2 个答案:

答案 0 :(得分:2)

我相信你可以扫描你的搜索。假设您在名为centerWordIndex的变量中有索引。然后,您可以根据whitechars拆分字符串,并在单词的开头和结尾添加单词,直到每个单词都没有单词,或者直到您的字符串大小与标签的大小相匹配。

你觉得怎么样??

答案 1 :(得分:0)

您需要启动的数据是:

  • 标签的宽度(称之为labelWidth)
  • 要居中的单词的宽度(称之为wordWidth)

然后你必须使用的每一面的大小是(labelWidth - wordWidth)/ 2.不要担心使用这个值,它只是目标。

您可以使用

来计算NSString的大小
CGSize newSize = [myString sizeWithFont: myFont];
CGFloat newWidth = newSize.width;

算法的目标应该是继续在居中单词的每一侧添加单词并重新计算每一步的总宽度。如果您已超过labelWidth,则无法再从该方向添加该单词。因此,在伪代码中,一种方法是:

calculate labelWidth and wordWidth
set currentWidth to wordWidth
set currentLeftPosition to position of first letter of word
set currentRightPosition to position of last letter of word
set currentString to word
set currentImbalance to 0

algorithm  start:
scan for position of 2 spaces to left of currentLeftPosition or start of string
    set leftTrialPosition to position found
    set leftTrialString as between leftTrialPosition and currentRightPosition inclusive
    calculate trialLeftWidth of leftTrialString
scan for position of 2 spaces to right of currentRightPosition or end of string
    set rightTrialPosition to position found
    set rightTrialString as between currentLeftPosition and rightTrialPositon inclusive
    calculate trialRightWidth of rightTrialString

if (trialLeftWidth - currentImbalance <= trialRightWidth 
&& trialLeftWidth <= labelWidth
&& trialLeftWidth != currentWidth)
    set currentImbalance -= calculate width of string from leftTrialPosition to currentLeftPosition 
    set currentLeftPosition = leftTrialPosition
    set currentWidth = trialLeftWidth
    set currentString = leftTrialString
else if (same checks for right)
    same steps using right data
else if (both left and right are larger than label or both sides no longer grow bigger)
    algorithm is done - return here

recurse to algorithm start

使用此基本策略,您可以在整个算法中跟踪左侧不平衡(负面)或右侧不平衡(正面),并优先相应地添加左侧或右侧单词,直到您拥有可以放在标签上的最大字符串或你已经使用了完整的字符串。这里关键的iOS特定部分是计算宽度的NSString方法。