![](/img/trans.png)
[英]How to show dynamic label on image view programmatically in Swift 2
[英]How to create dynamic label size programmatically in swift?
我正在嘗試在Swift中以編程方式創建標簽,但是我遇到的問題是,根據數據模型,文本量可能會發生變化,從而改變標簽的大小。 通常,在了解文本之前,我會像這樣創建標簽:
headerLabel.frame = CGRect(x: 0, y: 0, width: screenSize.width/2.5, height: screenSize.height/45)
headerLabel.center = CGPoint(x: screenSize.width/2, y: 245)
但是在這種情況下,文本可以是任意大小,從一行到一個段落,因此很難對高度進行編碼。 如何創建標簽以容納任意數量的文本?
在給文本加上標簽之后,您就可以訪問標簽的固有屬性,然后就可以給出框架了。
斯威夫特3:
let label = UILabel()
label.text = "Your text here"
label.textAlignment = .center
label.font = UIFont.systemFont(ofSize: 14)
label.frame = CGRect(x:0,y:0,width:label.intrinsicContentSize.width,height:label.intrinsicContentSize.height)
您可以根據internalContentSize檢查某些條件。
希望能幫助到你。
該標簽具有定義的寬度,但沒有定義的高度。 高度由標簽中的文本量決定。 如果刪除寬度,標簽將不會分成幾行,這不是您想要的。 最后sizeToFit()
方法在知道基於標簽的文本需要分成多少行文本之后,設置標簽的高度。 如果這不是您想要的,請告訴我。
let label = UILabel()
label.text = "scones"
label.numberOfLines = 0 // 0 = as many lines as the label needs
label.frame.origin.x = 32
label.frame.origin.y = 32
label.frame.size.width = view.bounds.width - 64
label.font = UIFont.displayHeavy(size: 17) // my UIFont extension
label.textColor = UIColor.black
label.sizeToFit()
view.addSubview(label)
您可以使用以下內容來計算字符串的高度和寬度,然后進行設置:
import Foundation
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let width = "Hello World".stringWidth // 74.6
let height = "Hello World".stringHeight // 16.7
let headerLabel = UILabel()
headerLabel.frame = CGRect(x: 0, y: 0, width: width, height: height)
headerLabel.center = CGPoint(x: screenSize.width/2, y: 245)
}
}
extension String {
var stringWidth: CGFloat {
let constraintRect = CGSize(width: UIScreen.main.bounds.width, height: .greatestFiniteMagnitude)
let boundingBox = self.trimmingCharacters(in: .whitespacesAndNewlines).boundingRect(with: constraintRect, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 14)], context: nil)
return boundingBox.width
}
var stringHeight: CGFloat {
let constraintRect = CGSize(width: UIScreen.main.bounds.width, height: .greatestFiniteMagnitude)
let boundingBox = self.trimmingCharacters(in: .whitespacesAndNewlines).boundingRect(with: constraintRect, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 14)], context: nil)
return boundingBox.height
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.