我從給定的字符串計算矩形的問題。計算給定字符串的標籤的正確大小
這裏是我的字符串:
_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)];
}
而且結果:
黃色背景是屏幕的一半寬度(160點)。綠色背景是另外的160分。我想擁有最大尺寸等於半屏寬度的_nameLabel。 任何人有任何想法如何正確計算它?問題也在代碼中評論。預先感謝您的幫助。
注:我正在開發一個僅適用於iOS7的應用程序。
編輯: 請注意,如果_name會短得多,例如「鑰匙」,我想有_valueLabel旁邊_nameLabel這樣的(和它的作品,因爲它應該):
好...... if(nameLabel.frame.size.width> 160){/ * reset to 160 * /}'? – 2014-01-21 14:17:59
爲什麼不使用Autolayout?它可以幫助你擺脫這些計算。 – NoilPaw
@ H2CO3和NoilPaw查看我的編輯。我需要先計算給定的字符串長度,然後將幀設置爲兩個標籤。按照您的建議,沒有好的方法來編寫條件。 boundingRectWithSize方法應該返回適當的值,但爲什麼它不? – Neru