2014-01-21 3 views
0

주어진 문자열에서 rect 계산에 문제가 있습니다.주어진 문자열에 대한 레이블의 적절한 크기 계산하기

_name = @"Any veryveryveryvery key here:"; 
_value = @"Any very very very very long value"; 

내 layoutSubviews 방법 :

- (void)layoutSubviews { 
    [super layoutSubviews]; 

    CGRect rect = self.contentView.bounds; 
    CGFloat verticalMargin = 5.0f; 

    //calculate rect for given name string: 
    CGFloat halfScreen = CGRectGetMidX(rect); //160points in portrait 

    //_nameLabel: 
    CGRect nameRect = 
    [_name boundingRectWithSize:CGSizeMake(halfScreen, CGRectGetHeight(rect)) 
         options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) 
        attributes:@{NSFontAttributeName: [UIFont fontWithName:kHelveticaFont size:_nameLabel.font.pointSize]} 
         context:nil]; 

    //name rect = origin=(x=0, y=0) size=(width=147.53174, height=34.5) - WHY width = 147.53174 NOT halfScreen = 160points? 

    [_nameLabel setFrame:CGRectMake(0.0f, 
            verticalMargin, 
            ceilf(CGRectGetWidth(nameRect)), 
            CGRectGetHeight(rect) - verticalMargin * 2)]; 

    //calculate rect for given value string: 
    //_valueLabel: 
    CGFloat maxWidth = CGRectGetWidth(rect) - CGRectGetMaxX(_nameLabel.frame); //172points in portrait 
    CGRect valueRect = 
    [_value boundingRectWithSize:CGSizeMake(maxWidth, CGRectGetHeight(rect)) 
         options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) 
         attributes:@{NSFontAttributeName: [UIFont fontWithName:kHelveticaFont size: _valueLabel.font.pointSize]} 
         context:nil]; 
    //valueRect = origin=(x=0, y=0) size=(width=160.03418, height=34.5) - WHY width = 160.03418 NOT maxWidth = 172 points? 

    [_valueLabel setFrame:CGRectMake(CGRectGetMaxX(_nameLabel.frame), 
            verticalMargin, 
            ceilf(CGRectGetWidth(valueRect)), 
            CGRectGetHeight(rect) - verticalMargin * 2)]; 

} 

그리고 결과 :

enter image description here

노란색 배경 화면의 절반 폭은 (160 점 여기

내 문자열). 녹색 배경은 160 포인트입니다. _nameLabel의 최대 크기가 화면 너비의 절반과 같아야합니다. 누구나 올바르게 계산하는 방법을 알고 있습니까? 질문은 코드에서 주석 처리됩니다. 도움을 위해 미리 감사드립니다.

참고 : iOS7 용 앱만 개발하고 있습니다.

편집 : 주, _name이 훨씬 짧아집니다 경우, 예를 들어 "키"를, 내가 같이 _nameLabel 할 _valueLabel 다음이 원하는 것을 (그리고 그것이 작동 예상대로) :

enter image description here

+1

음 ... if (nameLabel.frame.size.width> 160) {/ * 160 * /}으로 재설정 '? –

+1

Autolayout을 사용하지 않는 이유는 무엇입니까? 이 계산을 제거하는 데 도움이 될 수 있습니다. – NoilPaw

+0

@ H2CO3 및 NoilPaw가 편집을 참조하십시오. 먼저 지정된 문자열 길이를 계산 한 다음 프레임을 두 레이블로 설정해야합니다. 제안한대로 조건을 작성하는 좋은 방법이 없습니다. boundingRectWithSize 메서드는 적절한 값을 반환해야하지만 그렇지 않은 이유는 무엇입니까? – Neru

답변

2

내 문제가 해결되었습니다. 사실은 내가 사과 설명서에 깊은 다이빙과 문제는이 인수에 의해 생성 된 : 라인

NSStringDrawingUsesLineFragmentOrigin // which means: The specified origin is the line fragment origin, not the base line origin 

:

options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) 

그게 방법은 이유 :

(CGRect)boundingRectWithSize:options:attributes:context: 

나 잘못된 RECT 치수를했다. 이제는 모든 것이 제대로 작동합니다.

0
_valueLabel.text = _value; 
CGSize fitSize = [_valueLabel sizeThatFits:CGSizeMake(FLT_MAX, 18.0)]; 
CGRect newFrame = _valueLabel.frame; 
newFrame.size.width = if fitSize.width > 160.0 ? 160.0 : fitSize.width 
_valueLabel.frame = newFrame; 

분명히 코드에는 두 번째 UITextField를 이동하는 계산이 몇 가지 더 있지만 두 번째 UITextField의 원점과 마진을 계산하기 위해 위의 fitSize와 동일한 값을 사용하십시오. 희망은 당신의 문제를 해결하는 데 도움이됩니다.

관련 문제