本文為 Eul 樣章,如果您喜歡,請移步 AppStore/Eul 查看更多內容,
Eul 是一款 SwiftUI & Combine 教程 App(iOS、macOS),以文章(文字、圖片、代碼)配合真機示例(Xcode 12+、iOS 14+,macOS 11+)的形式呈現給讀者,筆者意在盡可能使用簡潔明了的語言闡述 SwiftUI & Combine 相關的知識,使讀者能快速掌握并在 iOS 開發中實踐,
重寫 alignmentGuide
SwiftUI 為我們提供了多種默認的對齊方式,如 .top,.bottom,.center 等,如下是將蘋果的 logo 和 文字 “Apple” 對齊的代碼:
HStack(alignment: .bottom) {
Image(systemName: "applelogo")
.font(.largeTitle)
Text("Apple")
}
如果我們想把文字 “Apple” 往上移動一些,換言之,文字的底部略高于于 logo 的底部,可以通過重寫 alignmentGuide 實作:
HStack(alignment: .bottom) {
Image(systemName: "applelogo")
.font(.largeTitle)
.alignmentGuide(.bottom, computeValue: { d in d[.bottom] - 5})
Text("Apple")
}
computeValue 閉包中回傳的是一個 ViewDimensions 結構體實體,它有 height、width 屬性供我們使用,還可以通過下標獲取指定的對齊方式,
上例我們簡單演示了重寫 alignmentGuide 的方法,當然,對于這種簡單的情況,我們還可以使用 offset 實作:
HStack(alignment: .bottom) {
Image(systemName: "applelogo")
.font(.largeTitle)
.offset(x: 0, y: 5)
Text("Apple")
}
自定義 alignmentGuide
VStack {
HStack {
Text("手機")
Text("155********")
}
HStack {
Text("電子郵箱")
Text("[email protected]")
}
}
如上是一個常見的界面,通常我們會使手機和郵箱右對齊(或者第二列的文字左對齊),通過系統默認的對齊方式,是無法實作的,我們需要自定義 alignmentGuide:
extension HorizontalAlignment {
struct CustomAlignment: AlignmentID {
static func defaultValue(in context: ViewDimensions) -> CGFloat {
return context[.trailing]
}
}
static let custom = HorizontalAlignment(CustomAlignment.self)
}
通過實作 AlignmentID 協議的方法,我們指定自定義的對齊方式為尾部對齊,然后我們使用自定義的對齊方式:
VStack(alignment: .custom) {
HStack {
Text("手機")
.alignmentGuide(.custom, computeValue: { $0[.trailing] })
Text("155********")
}
HStack {
Text("電子郵箱")
.alignmentGuide(.custom, computeValue: { $0[.trailing] })
Text("[email protected]")
}
}
看看示例所示的效果,與我們的預期是一致的,
iOS 開發,獨立作品: ① Eul:SwiftUI & Combine 簡明教程 ② FontsX:在任意 app 輸入特殊字體 詳情請戳: https://apps.apple.com/cn/developer/ke-zeng/id1322330151本文為 Eul 樣章,如果您喜歡,請移步 AppStore/Eul 查看更多內容,
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/308625.html
標籤:iOS
