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

标签 ios objective-c ios7 nsstring uilabel

我有两个 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/

相关文章:

ios - "Unable to simultaneously satisfy constraints"隐藏 View 上的 UIStackView "squished"

objective-c - 是否可以通过 Objective-C 中的字符串名称检索结构属性?

objective-c - 启用 AppSand 盒时如何从 USB 大容量存储设备读取数据

javascript - 从 iOS 中的 Safari 打开 Google Chrome 中的网页

ios7 - 类似 IOS 7 天气 APP 的过渡/动画

ios - 将 canDisplayBannerAds 更改为 NO 不会更新 View 以删除广告横幅

iphone - 远程调试iOS应用程序

ios - Storyboard线程错误

ios - 根据标签突出显示按钮?

ios - 四舍五入到n位小数