2011-08-05 1 views
11

NSString이 있고 적절한 UILabel을 만들기 위해 높이를 알고 싶습니다. 이NSString 높이 가져 오기

NSString *string = @"this is an example"; 
CGSize size = [string sizeWithFont:[UIFont systemFontOfSize:10.0f] 
          forWidth:353.0 
        lineBreakMode:UILineBreakModeWordWrap]; 
float height = size.height; 

높이를하는

지금은 13.0이다. 나는이 문자열

NSString *string = @"this is an example this is an example this is an example 
        this is an example this is an example this is an example 
        this is an example this is an example this is an example 
        this is an example this is an example this is an example 
        this is an example this is an example this is an example 
        this is an example "; 

높이 (그건 불가능, 폭과 함께 353)는 항상 13.0이다 사용하는 경우 ... 무슨 내가 잘못 뭐하는 거지?

ADD : 그것은 lineBreakMode이 정확하지 않은 경우처럼, 그래서

size.width; 

이 ... 잘 작동 ...하지만 그것은, 그렇지?

+0

을한다. 개체가 아니라 방금 만든 CGSize. 그건 오타예요? –

+0

하지만 'sizeWithFont : forWidth : lineBreakMode'는 NSString (예 : UILabel이 아닙니다)을 취합니다. – JAA

+0

그것은 그것을 받아들이지 않습니다, 말하자면, 그것은 그것에 행동하고, 당신에게 크기를 돌려줍니다. 그러므로 'float height = string.height;'를'float height = size '로 변경하면된다.높이;', 나는 그것을 더 이해할 것 같아요. –

답변

21

-sizeWithFont:constrainedToSize:lineBreakMode: 

가 반면

– sizeWithFont:forWidth:lineBreakMode: 

"는 한 줄의 텍스트를위한 컴퓨팅 통계"에 대한이기 때문에 당신이 기대하는대로 작동하지 않습니다 무슨 일을하는지 그 이유는 "여러 행의 텍스트에 대한 계산 메트릭". documentation에서 : 한 줄의 텍스트에 대한

컴퓨팅 통계

– sizeWithFont: 
– sizeWithFont:forWidth:lineBreakMode: 
– sizeWithFont:minFontSize:actualFontSize:forWidth:lineBreakMode: 

컴퓨팅 메트릭은 여러 줄의 텍스트에 대한

– sizeWithFont:constrainedToSize: 
– sizeWithFont:constrainedToSize:lineBreakMode: 

대신 예를 -sizeWithFont:constrainedToSize:lineBreakMode:를 사용해보십시오

CGSize maximumLabelSize = CGSizeMake(353,9999); 

CGSize expectedLabelSize = [string sizeWithFont:label.font       
           constrainedToSize:maximumLabelSize 
            lineBreakMode:label.lineBreakMode]; 

CGRect newFrame = label.frame; 
newFrame.size.height = expectedLabelSize.height; 
label.frame = newFrame; 
+0

죄송합니다, 여기 잘못 썼습니다 (지금은 올바른 것입니다)! 물론, Xcode에서 맞았습니다 (그리고 로그는 13.0입니다) – JAA

+0

예! 그게 효과가있어 !! 고맙습니다!!! – JAA

+0

이것은 하나의 메소드로 수행 할 수있는 코드에 너무 많은 코드입니다. 그리고 나는 downvote, LOL을 얻는다. –

1

이 방법은 지정된 폭에 제한 문자열의 폭과 높이를 반환 Documentation

에 따르면이 내가 일반적으로 할 것입니다. 줄 바꿈이 이되는 위치를 계산하지만 이 메서드는 실제로 텍스트를 추가 줄로 줄 바꿈하지 않습니다. 문자열의 크기가 지정된 너비를 초과하는 경우이 메서드 은 최대 너비를 준수 할 때까지 지정된 줄 중단 모드를 사용하여 텍스트를 자릅니다 (레이아웃 목적으로 만). 그 다음 결과 잘림 문자열의 크기 인 을 반환합니다.

당신이 사용하는해야 - [있는 NSString sizeWithFont : constrainedToSize : lineBreakMode :] 비슷한 동작을 가지고 있지만 전달 된 크기의 높이로 CGFLOAT_MAX을 uuse 수 있습니다 당신은 문자열에서 그 크기를 복용하고