Objective-C では、以下を使用できました。
CGSize stringsize =
[strLocalTelefone sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14.0f]}];
しかし、Swift Language では、この状況に対する解決策は見つかりませんでした。
ヘルプはありますか?
私がしたことは次のようなものです:
let myString = "Some text is just here..."
let size: CGSize = myString.size(withAttributes: [.font: UIFont.systemFont(ofSize: 14)])
let myString = "Some text is just here..."
let size: CGSize = myString.size(withAttributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 14)])
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)])
var originalString: String = "Some text is just here..."
let myString: NSString = originalString as NSString
let size: CGSize = myString.sizeWithAttributes([NSFontAttributeName: UIFont.systemFontOfSize(14.0)])
たった1行の解決策:
yourLabel.intrinsicContentSize.width
Objective-C / Swift用
これは、ラベル テキストにカスタム テキスト間隔がある場合でも機能します。
このコードを使用することもできます。より簡単で、NSString オブジェクトを取得するためだけに新しい変数を作成する必要はありません。
var stringToCalculateSize:String = "My text"
var stringSize:CGSize = (stringToCalculateSize as NSString).sizeWithAttributes([NSFontAttributeName: UIFont.systemFontOfSize(14.0)])
xCode 6.3 では、次のことを行う必要があります。
let font:AnyObject = UIFont(name: "Helvetica Neue", size: 14.0) as! AnyObject
let name:NSObject = NSFontAttributeName as NSObject
let dict = [name:font]
let textSize: CGSize = text.sizeWithAttributes(dict)
xCode 8.0 では、次のようにする必要があります: let charSize = string.size(attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 20)])