Swift中的CGSize sizeWithAttributes

Nal*_*pes 49 ios cgsize swift

在Objective-C中我能够使用:

    CGSize stringsize =
     [strLocalTelefone sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14.0f]}];
Run Code Online (Sandbox Code Playgroud)

但在Swift语言中,我没有找到任何解决方案.

任何帮助?

hol*_*lex 143

我做的是这样的:

swift 4.x

let myString = "Some text is just here..."
let size: CGSize = myString.size(withAttributes: [.font: UIFont.systemFont(ofSize: 14)])
Run Code Online (Sandbox Code Playgroud)

迅捷3

let myString = "Some text is just here..."
let size: CGSize = myString.size(withAttributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 14)])
Run Code Online (Sandbox Code Playgroud)

swift 2.x

var originalString: String = "Some text is just here..."
let myString: NSString = originalString as NSString
let size: CGSize = myString.size(attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 14.0)])
Run Code Online (Sandbox Code Playgroud)

  • @Developer,行`let size:CGSize = myString.sizeWithAttributes([NSFontAttributeName:UIFont(名称:"Helvetica",大小:15.0)!])`对我来说没有问题,我不知道你去过哪里坚持住. (2认同)

Fir*_*iro 8

只需使用显式转换:

var stringsize = (strLocalTelefone as NSString).sizeWithAtt...
Run Code Online (Sandbox Code Playgroud)

否则你也可以桥接它:
在更高版本的Swift中不再支持桥接.

var strLocalTelefone = "some string"
var stringsize = strLocalTelefone.bridgeToObjectiveC().sizeWithAttributes([NSFontAttributeName:UIFont.systemFontOfSize(14.0)])
Run Code Online (Sandbox Code Playgroud)

这个答案至少值得关注,因为它突出了两种方法之间的潜在差异.


Alo*_*lok 6

只需一行解决方案:

yourLabel.intrinsicContentSize.width for Objective-C/Swift

这甚至可以使您的标签文本具有自定义文本间距.