import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
setup()
}
private func setup() {
let container = UIView()
container.backgroundColor = .red
view.addSubview(container)
container.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
container.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
container.heightAnchor.constraint(equalToConstant: 100.0),
container.widthAnchor.constraint(equalToConstant: 100.0)
])
let label = UILabel()
label.text = "This is my text.This is my text.This is my text.This is my text.This is my text.This is my text.This is my text."
label.numberOfLines = 0
label.sizeToFit()
container.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
label.widthAnchor.constraint(equalTo: container.widthAnchor)
])
}
}
我有一個 100x100 UIView,我想在其中添加一個UILabel. UILabel溢位UIView. 我想知道我怎樣才能UILabel在里面UIView不溢位?
我試過,
label.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
label.topAnchor.constraint(equalTo: container.topAnchor),
label.bottomAnchor.constraint(equalTo: container.bottomAnchor),
label.widthAnchor.constraint(equalTo: container.widthAnchor)
])
但這出于某種原因增加了垂直填充,

激活這些約束還有另一個問題,那就是當文本長度很小時,文本垂直居中。我想總是把它釘在左上角。

uj5u.com熱心網友回復:
以下是我對正在發生的事情的看法。
我將從填充位開始。我相信這兩種情況實際上是相同的:

默認行為是使文本居中,在這兩種情況下都會發生這種情況。在第二種情況下(右圖),您說有一個填充,UILabel 不能以該字體大小容納另一行文本,因此它停在第 4 行并將文本與標簽的框架居中。
例如,如果將標簽高度增加到 500,您將看到它不是隨機填充,而是居中。
這是給定高度可能支持多少行文本的簡單近似值。
let label = UILabel()
label.text = "This is my text.This is my text.This is my text.This is my text.This is my text.This is my text.This is my text."
label.numberOfLines = 0
label.sizeToFit()
// I added these line
print("Max lines that will fit: \(floor(100.0 / label.font.lineHeight))")
print("Max lines that will fit: \(floor(130.0 / label.font.lineHeight))")
列印出來的答案是 4.0 和 6.0。當我將標簽高度增加到 130 時,如下所示,它給了我 6 行近似值:
// Inside your set up function
container.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
container.leadingAnchor.constraint(equalTo: view.leadingAnchor),
container.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
container.heightAnchor.constraint(equalToConstant: 130.0),
container.widthAnchor.constraint(equalToConstant: 100.0)
])
let label = UILabel()
label.text = "This is my text.This is my text.This is my text.This is my text.This is my text.This is my text.This is my text."
label.numberOfLines = 0
label.sizeToFit()

所以我希望這能解釋關于填充的一點。
現在談到如何防止溢位,我認為您的自動布局已經防止了這種情況。我認為clipsToBounds在容器上添加也可以防止標簽溢位。
最后,將標簽與頂部對齊是一個完全不同的問題。然而,
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/416819.html
標籤:
