我从给定字符串计算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)];
}
结果:
黄色背景是屏幕的一半宽度(160点)。绿色背景是另外160点。我希望_nameLabel的最大大小等于半屏宽度。 任何人都知道如何正确计算它?问题也在代码中评论。提前感谢您的帮助。
注意:我正在开发仅适用于iOS7的应用程序。
编辑: 请注意,如果_name会短得多,例如“key”,我希望_nameLabel旁边有_valueLabel(就像它应该的那样):
答案 0 :(得分: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:
给了我错误的矩形尺寸。现在一切正常。
答案 1 :(得分: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,但因此使用上面相同的fitSize来计算第二个UITextField的原点加上您的边距。希望有助于解决您的问题。