如何获取 NSString 的宽度? [英] How to get the width of an NSString?

查看:24
本文介绍了如何获取 NSString 的宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取 NSString 的宽度(例如 NSString *myString = @"hello").有没有办法做到这一点?

I am trying to get the width of an NSString (ex. NSString *myString = @"hello"). Is there a way to do this?

谢谢.

推荐答案

这里有一个相对简单的方法.只需使用适当的字体创建一个 NSAttributedString 并询问其大小:

Here's a relatively simple approach. Just create an NSAttributedString with the appropriate font and ask for its size:

- (CGFloat)widthOfString:(NSString *)string withFont:(NSFont *)font {
     NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
     return [[[NSAttributedString alloc] initWithString:string attributes:attributes] size].width;
 }

这篇关于如何获取 NSString 的宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆