确定使用 NSString draw/size 方法绘制什么子字符串

发布于 2024-11-27 17:56:49 字数 547 浏览 2 评论 0原文

有没有什么方法可以确定在给定空间中可以渲染多少 NSString?

我知道所有 NSString sizeWithFont 方法(例如 sizeWithFont:constrainedToSize:lineBreakMode:)。如果字符串太长而无法容纳,这些不会告诉您字符串的哪一部分能够被渲染。

例如,如果我有

NSString *testString = @"The brown dog";

And I call:

[testString sizeWithFont:[UIFont systemFontOfSize:17] constrainedtoSize:CGSizeMake(20, 20) lineBreakMode:UILineBreakModeWordWrap];

我可能会返回 CGSize = {20,20}。这告诉我绳子至少占据了整个尺寸,但它并没有告诉我它是否已经结束,或者能够容纳多少。如果只有“棕色”能够适合,我想知道这一点。

也许有一些核心基础方法可以做到这一点?

Is there any method to determine how much of an NSString can be rendered in a given space?

I know about all the NSString sizeWithFont methods (e.g. sizeWithFont:constrainedToSize:lineBreakMode:). If the string is too long to fit though, these don't tell you what portion of the string was able to be rendered.

For example, if I have

NSString *testString = @"The brown dog";

And I call:

[testString sizeWithFont:[UIFont systemFontOfSize:17] constrainedtoSize:CGSizeMake(20, 20) lineBreakMode:UILineBreakModeWordWrap];

I may get back a CGSize = {20,20}. That tells me the string took at least the entire size, but it doesn't tell me if it was over, or how much was able to fit. If only "The brown" was able to fit, I'd like to know that.

Maybe some Core Foundation methods to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

听风吹 2024-12-04 17:56:49

判断是否要截断的一种方法是在约束矩形中提供非常大的高度。如果返回的高度高于标签的高度,您就知道它将被截断。像这样的事情:

    // myLabel is a UILabel*
    CGSize labelSize = myLabel.frame.size;
    labelSize.height = 9999;
    CGSize newSize = [newLabel sizeWithFont:[UIFont systemFontOfSize:17.0] 
                            constrainedToSize:labelSize 
                                lineBreakMode:UILineBreakModeWordWrap];
    if( newSize.height > labelSize.height ) {
        // Whoops, too big!
    }

它会告诉你它是否会被截断,但它不会告诉你它会被截断多少。我能想到的唯一方法是循环执行此操作,每次从末尾删除一个单词,直到它适合为止。

One way to tell if it's going to truncate is to provide a very large height in the constrain rect. If the height that comes back is taller than the height of your label, you know it would be truncated. Something like this:

    // myLabel is a UILabel*
    CGSize labelSize = myLabel.frame.size;
    labelSize.height = 9999;
    CGSize newSize = [newLabel sizeWithFont:[UIFont systemFontOfSize:17.0] 
                            constrainedToSize:labelSize 
                                lineBreakMode:UILineBreakModeWordWrap];
    if( newSize.height > labelSize.height ) {
        // Whoops, too big!
    }

That will tell you if it would be truncated, but it won't tell you how much of it would be. Only way I can think to do that would be to do this in a loop, removing a word off the end each time until it fits.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文