下準備
まず、表示する文字列に合わせてラベルの高さを変えるので以下のことが前提になります。
label.numberOfLinesの設定値を0にする(ラベルの行数制限をなくす)
sizeToFitメソッドを使う
以下のようにすると、文字列の長さに応じてラベルの高さを設定することができます。
import UIKit
class FirstViewController : UIViewController {
@IBOutlet var label : UILabel!
override func viewDidLoad() {
super.viewDidLoad()
label.backgroundColor = UIColor.orange
label.numberOfLines = 0;
label.text = "We can look six like stars from the first magnitude. "
+ "the first magnitude is that big star. We can hardly look six like stars. "
+ "But they look smaller than they actually is because six like stars is "
+ "far from earth. In actually, six like stars may be more than ten times "
+ "as big as the first magnitude. Many people who isn't shine like "
+ "six like stars exist in the world."
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.sizeToFit()
}
}
実行結果
|
sizeThatFitsメソッドを使う
これはあらかじめ指定したサイズを元にサイズの変更(今回の場合は高さの設定)するのに使えます。
sizeThatFitsメソッドは、サイズの最大値に収まる範囲で、文字列の長さに応じたサイズを返してくれます。
import UIKit
class FirstViewController : UIViewController {
@IBOutlet var label : UILabel!
override func viewDidLoad() {
super.viewDidLoad()
label.backgroundColor = UIColor.orange
label.numberOfLines = 0;
label.text = "We can look six like stars from the first magnitude. "
+ "the first magnitude is that big star. We can hardly look six like stars. "
+ "But they look smaller than they actually is because six like stars is "
+ "far from earth. In actually, six like stars may be more than ten times "
+ "as big as the first magnitude. Many people who isn't shine like "
+ "six like stars exist in the world."
label.lineBreakMode = NSLineBreakMode.byWordWrapping
// 幅の最大値は現在の幅、高さはCGFloatの最大値(事実上の無制限)
let maxSize : CGSize = CGSize.init(width: label.frame.size.width, height: CGFloat.greatestFiniteMagnitude)
var labelFrame : CGRect = label.frame
labelFrame.size.height = label.sizeThatFits(maxSize).height
label.frame = labelFrame
}
}
実行結果
|
二つとも同じ結果になりましたね。
うまく使い分けてください!