我想 button 的 top 與 button 的 titleLabel 的 top 對齊,所以我在 xib 中將內容垂直對齊設定為 top 。這在 xib 中效果很好,但是在構建之后,titleLabel 似乎仍然是中心垂直對齊的布局。我錯過了什么?

uj5u.com熱心網友回復:
首先,評論:您在 Storyboard / Interface Builder 中看到的內容:
- 并不總是UIKit 在模擬器中呈現的那樣
- 這并不總是UIKit在設備上呈現的內容
這就是我們在不同的模擬器和設備上測驗、測驗、測驗的原因。
那么,這里發生了什么?
UIKit 使用按鈕的框架.titleLabel來確定按鈕的固有大小。
對于默認按鈕,沒有明確設定寬度或高度,UIKit6-pts在頂部和底部插入標題標簽。
這里有 2 個按鈕 - 都沒有高度限制。按鈕 1是默認的中心/中心內容對齊方式,按鈕 2設定為左/上。按鈕標題標簽背景是青色的,所以我們可以很容易地看到它的框架。
故事板/IB:

運行:

除錯視圖層次結構(注意標簽框架與按鈕框架):

因此,對于 18 磅系統字體,標題標簽高度為21.0... add 6-ptstop 和 bottom 并且按鈕框架高度為33-pts.
將 Control Alignment 設定為 Top / Center / Bottom 或 Fill 都沒有關系... UIKit 仍然采用標簽高度并添加6-ptsTop 和 Bottom “填充”。
如何獲得實際的頂部對齊?讓我們看幾個方法。
以下是堆疊視圖中的 6 個按鈕:

按鈕 1位于默認中心/中心,沒有高度限制。
正如我們所見,按鈕 2具有 Control Alignment Left / Top ... 但對垂直對齊沒有影響。
Button 3 is also Left/Top, but let's give it an explicit Height (we'll use 80 to make things obvious). Looks better - but there is still 6-pts of "padding" added to the top of the title label.
Now, you may have seen this at the top of the Size Inspector panel:

This looks promising! Let's set the Title Insets Top to Zero!
Whoops -- it's already Zero?!?!?!?
Same thing with the Content Insets!
Turns out, if the the edge insets are at the default, the padding is added anyway.
We could try setting the Title Inset Top to -6 and, because labels center the text vertically, we'll also have to set the Bottom inset to 6. This works... but we may not want to rely on that value of 6 to be accurate in future iOS versions.
Button 4 - lets try Content Insets -> Bottom: 1 ... and it looks like we're on our way! The label is now top-aligned with the button frame!
So...
Button 5 - remove the Height: 80 constraint so we can use the default button height. D'oh! The button frame height is now title-label-height plus zero-top plus one-bottom...
Button 6 - finally, we'll use Content Insets -> Bottom: 1 with an explicit Height constraint of 33 (the default button height).
那么......如果我們不想設定顯式高度怎么辦?也許我們稍后會更改標題標簽的字體大小?還是我們遇到了其他問題?
您可以使用自定義UIButton子類。
這是一個示例,標記為@IBDesignable以便我們可以在 Storyboard / IB 中看到它的布局:
@IBDesignable
class MyTopLeftAlignedButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
commonInit()
}
func commonInit() {
self.contentVerticalAlignment = .top
self.contentHorizontalAlignment = .left
// if we want to see the title label frame
//titleLabel?.backgroundColor = .cyan
}
override var bounds: CGRect {
didSet {
if let v = titleLabel {
var t = titleEdgeInsets
let h = (bounds.height - v.frame.height) * 0.5
t.top = -h
t.bottom = h
titleEdgeInsets = t
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/416283.html
標籤:
