53

Objective-C では、以下を使用できました。

    CGSize stringsize =
     [strLocalTelefone sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14.0f]}];

しかし、Swift Language では、この状況に対する解決策は見つかりませんでした。

ヘルプはありますか?

4

6 に答える 6

159

私がしたことは次のようなものです:

スイフト5.x

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

スウィフト4.x

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

スイフト3

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)])

スウィフト 2.x

var originalString: String = "Some text is just here..."
let myString: NSString = originalString as NSString
let size: CGSize = myString.sizeWithAttributes([NSFontAttributeName: UIFont.systemFontOfSize(14.0)])
于 2014-06-10T13:21:48.067 に答える
7

たった1行の解決策:

yourLabel.intrinsicContentSize.widthObjective-C / Swift用

これは、ラベル テキストにカスタム テキスト間隔がある場合でも機能します。

于 2018-09-17T04:52:43.197 に答える
2

このコードを使用することもできます。より簡単で、NSString オブジェクトを取得するためだけに新しい変数を作成する必要はありません。

var stringToCalculateSize:String = "My text"
var stringSize:CGSize = (stringToCalculateSize as NSString).sizeWithAttributes([NSFontAttributeName: UIFont.systemFontOfSize(14.0)])
于 2015-03-26T09:49:38.930 に答える
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)
于 2015-04-21T06:26:38.317 に答える
-3

xCode 8.0 では、次のようにする必要があります: let charSize = string.size(attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 20)])

于 2016-10-19T05:31:56.367 に答える