gpt4 book ai didi

ios - 计算给定字符串的标签的适当大小

转载 作者:行者123 更新时间:2023-11-28 22:17:33 25 4
gpt4 key购买 nike

我在根据给定字符串计算矩形时遇到问题。

这是我的字符串:

_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 会更短,例如“key”,我希望像这样在 _nameLabel 旁边放置 _valueLabel(它应该可以正常工作):

enter image description here

最佳答案

我解决了我的问题。实际上我深入研究了苹果文档,问题是由这个论点产生的:

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

排队:

options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)

这就是为什么方法:

 (CGRect)boundingRectWithSize:options:attributes:context:

给我错误的矩形尺寸。现在一切正常。

关于ios - 计算给定字符串的标签的适当大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21260603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com