시작해야 할 데이터는 다음과 같습니다
- 라벨 (labelWidth를 호출)
- 당신이 중앙에 원하는 단어의 폭 (호출 wordWidth)의 폭
그러면 작업 할 각면의 크기는 (labelWidth - wordWidth)/2입니다.이 값을 사용하는 것에 대해 걱정하지 마십시오. 단지 대상 일뿐입니다.
당신은 중심 단어의 각면에 단어를 추가 계속해야
CGSize newSize = [myString sizeWithFont: myFont];
CGFloat newWidth = newSize.width;
알고리즘의 목표를 사용하여있는 NSString의 크기를 계산하는 기능을 사용하여 전체 너비 각 단계를 재 계산 할 수 있습니다 . 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 메서드입니다.
예를 들어 주시겠습니까? – metamorph
나는이 응답에 내 알고리즘을 기반으로했다. 당신의 도움에 감사드립니다! – metamorph
아무 문제 없음 :) 언제든지. – Moszi