2011-08-04 3 views
1

의 내부 문장에서 단어를 중앙에아이폰 OS : 알고리즘은 예를 들어, 내가 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> 

표시해야 : 당신의 최선

단어가 한쪽 끝 또는 기타에 가까운 경우

"내가 할 ... 노력하고 ... 문장의 당신에게 를 제공하기 위해" 적절한 양의 테를 센터링하고 표시합니다. XT 예 :

NSString myWord = @"my"; 

어떤 아이디어 "이것은 매우 긴 문장이 당신에게 무엇의 예를 제공하는 ...입니다"?

감사합니다.

답변

2

귀하의 검색 내용을 검색 할 수 있다고 생각합니다. centerWordIndex라는 변수에 색인이 있다고 가정 해 보겠습니다. 그런 다음 화이트 ars을 기반으로 문자열을 분할하고 각면에 단어가 없거나 문자열의 크기가 레이블의 크기와 일치 할 때까지 단어의 처음과 끝에 단어를 추가 할 수 있습니다.

당신은 어떻게 생각하십니까 :)?

+0

예를 들어 주시겠습니까? – metamorph

+0

나는이 응답에 내 알고리즘을 기반으로했다. 당신의 도움에 감사드립니다! – metamorph

+0

아무 문제 없음 :) 언제든지. – Moszi

0

시작해야 할 데이터는 다음과 같습니다

  • 라벨 (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 메서드입니다.

+0

매우 포괄적 인 대답 .. 나는 더 간단한 옵션이 가능할 수도 있다고 생각하지만? – metamorph