gpt4 book ai didi

ios - 使用 `boundingRectWithSize` 对齐动态帧中的 UILabel 时出现问题

转载 作者:搜寻专家 更新时间:2023-10-30 20:17:28 25 4
gpt4 key购买 nike

我有两个 UILabels L1 和 L2。

  • L1最大宽度为150
  • L1的最小宽度会根据文字长度调整
  • 两个标签之间的距离是10。

我的代码,

NSString *s = @"Stringwithoutspacetext";
L1.text = s;
L2.text = @"2";


CGSize textSize = { 150, 21 };
CGRect textRect = [[NSString stringWithFormat:@"%@",s]
boundingRectWithSize:textSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]}
context:nil];

L1.frame = CGRectMake(L1.frame.origin.x, L1.frame.origin.y, textRect.size.width, L1.frame.size.height);
L2.frame = CGRectMake(L1.frame.origin.x+textRect.size.width+10, L2.frame.origin.y, L2.frame.size.width, L2.frame.size.height);

当字符串 s 中没有空格时,它工作正常。

enter image description here

如果字符串有一个空格,即。 s = @"String withspacetext";

输出如下所示,

enter image description here

如果字符串有两个空格,即。 s = @"String with spacetext";

输出如下所示,

enter image description here

为什么空格文本会影响我的代码?我应该更改我的代码中的哪些内容才能在上述情况下正常工作?

最佳答案

已找到解决方案!

我只是用临时字符串中的 x 替换了空格,以找到 textrect 的大小。

NSString *s = @"String with spacetext";
L1.text = s;
L2.text = @"2";

NSString *tempstring =[s stringByReplacingOccurrencesOfString:@" " withString:@"x"];
CGSize textSize = { 150, 21 };
CGRect textRect = [[NSString stringWithFormat:@"%@",tempstring]
boundingRectWithSize:textSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]}
context:nil];

L1.frame = CGRectMake(L1.frame.origin.x, L1.frame.origin.y, textRect.size.width, L1.frame.size.height);
L2.frame = CGRectMake(L1.frame.origin.x+textRect.size.width+10, L2.frame.origin.y, L2.frame.size.width, L2.frame.size.height);

关于ios - 使用 `boundingRectWithSize` 对齐动态帧中的 UILabel 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24779430/

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