Данные, которые вам нужно запустить:
- ширина вашей метки (назовите ее 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, который вычисляет ширину.