Layout question for a numbered list in SwiftUI

I am working on a NumberedList component which works like the <ol> tag in HTML. I’d like to be able provide an arbitrary number of elements, that would be automatically numbered and laid out. However there is one aspect of the layout I can’t quite figure out.

I have created an OrderedList view (the equivalent of the <ol> HTML tag), which is using a _VariadicView.Tree and a custom _VariadicView_UnaryViewRoot layout.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>public struct OrderedList<Content: View>: View {
let content: Content
@Environment(.listLevel)
var level
public init(@ViewBuilder content: () -> Content) {
self.content = content()
}
public var body: some View {
let layout = OrderedListLayout(level: level)
_VariadicView.Tree(layout) {
content
}
}
}
struct OrderedListLayout: _VariadicView_UnaryViewRoot {
let level: ListLevel
@ViewBuilder
func body(children: _VariadicView.Children) -> some View {
let padding: Double = switch level {
case .first:
8
case .second, .third:
-6
}
VStack(alignment: .leading, spacing: 8) {
ForEach(Array(children.enumerated()), id: .element.id) { index, child in
HStack(alignment: .centerOfFirstLine, spacing: 8) {
Text(verbatim: "(index + 1).")
child
}
}
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.leading, padding)
}
}
</code>
<code>public struct OrderedList<Content: View>: View { let content: Content @Environment(.listLevel) var level public init(@ViewBuilder content: () -> Content) { self.content = content() } public var body: some View { let layout = OrderedListLayout(level: level) _VariadicView.Tree(layout) { content } } } struct OrderedListLayout: _VariadicView_UnaryViewRoot { let level: ListLevel @ViewBuilder func body(children: _VariadicView.Children) -> some View { let padding: Double = switch level { case .first: 8 case .second, .third: -6 } VStack(alignment: .leading, spacing: 8) { ForEach(Array(children.enumerated()), id: .element.id) { index, child in HStack(alignment: .centerOfFirstLine, spacing: 8) { Text(verbatim: "(index + 1).") child } } } .frame(maxWidth: .infinity, alignment: .leading) .padding(.leading, padding) } } </code>
public struct OrderedList<Content: View>: View {
    let content: Content
    
    @Environment(.listLevel)
    var level
    
    public init(@ViewBuilder content: () -> Content) {
        self.content = content()
    }
    
    public var body: some View {
        let layout = OrderedListLayout(level: level)
        
        _VariadicView.Tree(layout) {
            content
        }
    }
}

struct OrderedListLayout: _VariadicView_UnaryViewRoot {
    let level: ListLevel
    
    @ViewBuilder
    func body(children: _VariadicView.Children) -> some View {
        let padding: Double = switch level {
        case .first:
            8
        case .second, .third:
            -6
        }
        
        VStack(alignment: .leading, spacing: 8) {
            ForEach(Array(children.enumerated()), id: .element.id) { index, child in
                HStack(alignment: .centerOfFirstLine, spacing: 8) {
                    Text(verbatim: "(index + 1).")
                    
                    child
                }
            }
        }
        .frame(maxWidth: .infinity, alignment: .leading)
        .padding(.leading, padding)
    }
}

This list is meant to be used with a ListElement view (the equivalent of the <li> HTML tag), which can contain an arbitrary label and an optional child view.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>public struct ListElement<Label: View, Child: View>: View {
let label: Label
let child: Child?
@Environment(.listLevel)
var level
public init(@ViewBuilder label: () -> Label, @ViewBuilder child: () -> Child) {
self.label = label()
self.child = child()
}
public var body: some View {
VStack(alignment: .leading, spacing: 8) {
label
if let child {
child
.environment(.listLevel, level.next())
}
}
}
}
public extension ListElement where Child == EmptyView {
init(@ViewBuilder label: () -> Label) {
self.label = label()
self.child = nil
}
}
</code>
<code>public struct ListElement<Label: View, Child: View>: View { let label: Label let child: Child? @Environment(.listLevel) var level public init(@ViewBuilder label: () -> Label, @ViewBuilder child: () -> Child) { self.label = label() self.child = child() } public var body: some View { VStack(alignment: .leading, spacing: 8) { label if let child { child .environment(.listLevel, level.next()) } } } } public extension ListElement where Child == EmptyView { init(@ViewBuilder label: () -> Label) { self.label = label() self.child = nil } } </code>
public struct ListElement<Label: View, Child: View>: View {
    let label: Label
    
    let child: Child?
    
    @Environment(.listLevel)
    var level
    
    public init(@ViewBuilder label: () -> Label, @ViewBuilder child: () -> Child) {
        self.label = label()
        self.child = child()
    }
    
    public var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            label
            
            if let child {
                child
                    .environment(.listLevel, level.next())
            }
        }
    }
}

public extension ListElement where Child == EmptyView {
    init(@ViewBuilder label: () -> Label) {
        self.label = label()
        self.child = nil
    }
}

This screenshot shows the current result. I have added a green border to the numbering texts and blue border to the list elements to better show how they are not aligned. I would like to be able to lay out the elements so that the leading of all elements in the same list level are aligned. Essentially I want all numbering texts to have the same width.

I could have technically used a Grid to help with that kind of layout. However, I don’t think this would work since I want to be able to nest multiple lists if needed. I think the solution would probably lie in either using a custom HorizontalAlignment guide or a custom Layout, but I can’t quite wrap my head around it.

EDIT: I forgot to mention that my project has a deployment target of iOS 15. Nesting Grids actually works to achieve the layout I want, but doesn’t meet the deployment target.

1

Using a Grid works alright for me. I’m not sure why you would think it wouldn’t work with nested ordered lists. You’d just end up with nested Grids, and there is nothing wrong with that.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>struct OrderedListLayout: _VariadicView_UnaryViewRoot {
let level: ListLevel
@ViewBuilder
func body(children: _VariadicView.Children) -> some View {
let padding: Double = switch level {
case .first:
8
case .second, .third:
-6
}
Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 8, verticalSpacing: 8) {
ForEach(Array(children.enumerated()), id: .element.id) { index, child in
GridRow {
Text(verbatim: "(index + 1).")
.gridColumnAlignment(.trailing)
child
}
}
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.leading, padding)
}
}
</code>
<code>struct OrderedListLayout: _VariadicView_UnaryViewRoot { let level: ListLevel @ViewBuilder func body(children: _VariadicView.Children) -> some View { let padding: Double = switch level { case .first: 8 case .second, .third: -6 } Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 8, verticalSpacing: 8) { ForEach(Array(children.enumerated()), id: .element.id) { index, child in GridRow { Text(verbatim: "(index + 1).") .gridColumnAlignment(.trailing) child } } } .frame(maxWidth: .infinity, alignment: .leading) .padding(.leading, padding) } } </code>
struct OrderedListLayout: _VariadicView_UnaryViewRoot {
    let level: ListLevel
    
    @ViewBuilder
    func body(children: _VariadicView.Children) -> some View {
        let padding: Double = switch level {
        case .first:
            8
        case .second, .third:
            -6
        }
        
        Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 8, verticalSpacing: 8) {
            ForEach(Array(children.enumerated()), id: .element.id) { index, child in
                GridRow {
                    Text(verbatim: "(index + 1).")
                        .gridColumnAlignment(.trailing)
                    child
                }
            }
        }
        .frame(maxWidth: .infinity, alignment: .leading)
        .padding(.leading, padding)
    }
}

2

There are two ways to achieve this:

  • Create virtual nodes to calculate the desired width
  • Using onGeometryChange to calculate the max width of every numbering text

Here is a demo using the second method:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import SwiftUI
struct ListWithEqualNumberWidth: View {
@State private var numberWidth: CGFloat = 0
@State private var rows = [
"The standard Lorem Ipsum passage, used since the 1500s",
"Section 1.10.32 of de Finibus Bonorum et Malorum, written by Cicero in 45 BC",
"1914 translation by H. Rackham",
"Section 1.10.33 of de Finibus Bonorum et Malorum, written by Cicero in 45 BC",
"The standard Lorem Ipsum passage, used since the 1500s",
"Section 1.10.32 of de Finibus Bonorum et Malorum, written by Cicero in 45 BC",
"1914 translation by H. Rackham",
"Section 1.10.33 of de Finibus Bonorum et Malorum, written by Cicero in 45 BC",
"The standard Lorem Ipsum passage, used since the 1500s",
"Section 1.10.32 of de Finibus Bonorum et Malorum, written by Cicero in 45 BC",
"1914 translation by H. Rackham",
"Section 1.10.33 of de Finibus Bonorum et Malorum, written by Cicero in 45 BC",
"The standard Lorem Ipsum passage, used since the 1500s",
"Section 1.10.32 of de Finibus Bonorum et Malorum, written by Cicero in 45 BC",
"1914 translation by H. Rackham",
"Section 1.10.33 of de Finibus Bonorum et Malorum, written by Cicero in 45 BC",
]
var body: some View {
List(rows.indices, id: .self, rowContent: { index in
HStack {
ListNumber(number: index, onGeometryChange: { width in numberWidth = max(numberWidth, width) })
.frame(width: numberWidth + 10, alignment: .trailing)
Text(rows[index])
}
})
}
}
struct ListNumber: View {
var number: Int
var onGeometryChange: (CGFloat) -> Void
var body: some View {
HStack {
Text(number.description)
}
.onGeometryChange(
for: CGSize.self,
of: { proxy in proxy.size },
action: { onGeometryChange($0.width) }
)
}
}
</code>
<code>import SwiftUI struct ListWithEqualNumberWidth: View { @State private var numberWidth: CGFloat = 0 @State private var rows = [ "The standard Lorem Ipsum passage, used since the 1500s", "Section 1.10.32 of de Finibus Bonorum et Malorum, written by Cicero in 45 BC", "1914 translation by H. Rackham", "Section 1.10.33 of de Finibus Bonorum et Malorum, written by Cicero in 45 BC", "The standard Lorem Ipsum passage, used since the 1500s", "Section 1.10.32 of de Finibus Bonorum et Malorum, written by Cicero in 45 BC", "1914 translation by H. Rackham", "Section 1.10.33 of de Finibus Bonorum et Malorum, written by Cicero in 45 BC", "The standard Lorem Ipsum passage, used since the 1500s", "Section 1.10.32 of de Finibus Bonorum et Malorum, written by Cicero in 45 BC", "1914 translation by H. Rackham", "Section 1.10.33 of de Finibus Bonorum et Malorum, written by Cicero in 45 BC", "The standard Lorem Ipsum passage, used since the 1500s", "Section 1.10.32 of de Finibus Bonorum et Malorum, written by Cicero in 45 BC", "1914 translation by H. Rackham", "Section 1.10.33 of de Finibus Bonorum et Malorum, written by Cicero in 45 BC", ] var body: some View { List(rows.indices, id: .self, rowContent: { index in HStack { ListNumber(number: index, onGeometryChange: { width in numberWidth = max(numberWidth, width) }) .frame(width: numberWidth + 10, alignment: .trailing) Text(rows[index]) } }) } } struct ListNumber: View { var number: Int var onGeometryChange: (CGFloat) -> Void var body: some View { HStack { Text(number.description) } .onGeometryChange( for: CGSize.self, of: { proxy in proxy.size }, action: { onGeometryChange($0.width) } ) } } </code>
import SwiftUI

struct ListWithEqualNumberWidth: View {
    @State private var numberWidth: CGFloat = 0
    
    @State private var rows = [
        "The standard Lorem Ipsum passage, used since the 1500s",
        "Section 1.10.32 of de Finibus Bonorum et Malorum, written by Cicero in 45 BC",
        "1914 translation by H. Rackham",
        "Section 1.10.33 of de Finibus Bonorum et Malorum, written by Cicero in 45 BC",
        "The standard Lorem Ipsum passage, used since the 1500s",
        "Section 1.10.32 of de Finibus Bonorum et Malorum, written by Cicero in 45 BC",
        "1914 translation by H. Rackham",
        "Section 1.10.33 of de Finibus Bonorum et Malorum, written by Cicero in 45 BC",
        "The standard Lorem Ipsum passage, used since the 1500s",
        "Section 1.10.32 of de Finibus Bonorum et Malorum, written by Cicero in 45 BC",
        "1914 translation by H. Rackham",
        "Section 1.10.33 of de Finibus Bonorum et Malorum, written by Cicero in 45 BC",
        "The standard Lorem Ipsum passage, used since the 1500s",
        "Section 1.10.32 of de Finibus Bonorum et Malorum, written by Cicero in 45 BC",
        "1914 translation by H. Rackham",
        "Section 1.10.33 of de Finibus Bonorum et Malorum, written by Cicero in 45 BC",
    ]
    
    var body: some View {
        List(rows.indices, id: .self, rowContent: { index in
            HStack {
                ListNumber(number: index, onGeometryChange: { width in numberWidth = max(numberWidth, width) })
                    .frame(width: numberWidth + 10, alignment: .trailing)
                Text(rows[index])
            }
        })
    }
}

struct ListNumber: View {
    var number: Int
    var onGeometryChange: (CGFloat) -> Void
    
    var body: some View {
        HStack {
            Text(number.description)
        }
        .onGeometryChange(
            for: CGSize.self,
            of: { proxy in proxy.size },
            action: { onGeometryChange($0.width) }
        )
    }
}

The result would be

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật