iOS:在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";  

应该显示:

“……给你一个我想要的例子的句子……”

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

 NSString myWord = @"my"; 

“这是很长的句子给你一个例子……”

有任何想法吗?

谢谢。

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

你怎么看 :) ?

您需要启动的数据是:

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

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

您可以使用此function来计算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方法。