iosswiftuivstack

VStack Leading alignment doesn't work with nested Text Views


This is how my VStack is defined here:

VStack(alignment: .leading, spacing: 1) {
    Text("entry.titleAlert hajdfg dgfhds fghjds gfhjdsg fhjdsg2")
        .frame(maxWidth: .infinity)
        .multilineTextAlignment(.leading)
        .font(.caption)
        .padding(5)
        .background(Color(uiColor: .alertNews))
   

    Text("entry.contentAlert jhdsg fdhjsgf dhjsgf dhjsgf jdhsgf jdhsgf jdhsgf jdhsgf dhjsgf dhjsgf hdsgfh dghjf gsdhjgf dhjsgf dhjsgf dhjsg fjdhsg fjhdsgf jhdsgf jdhsgf dhjsgf jdhsgfhjdsg fhdsg fgdsjgfdhjs gfjdhsgf hs")
        .frame(maxWidth: .infinity)
        .multilineTextAlignment(.leading)
        .font(.caption)
        .opacity(0.7)
        .lineLimit(5)
        .padding(5)
        .background(Color(uiColor: .alertNews))
    Spacer()
}
.frame(maxWidth: .infinity, alignment: .leading)

and the effect is the following:

Why is it not left aligned?


Solution

  • The VStack leading alignment on the initialize function is for aligning all sub-views and on .frame function is to align with its parent. The same with two TextViews nested inside. You're using .frame with alignment = .center by default.

    @inlinable public func frame(minWidth: CGFloat? = nil, idealWidth: CGFloat? = nil, maxWidth: CGFloat? = nil, minHeight: CGFloat? = nil, idealHeight: CGFloat? = nil, maxHeight: CGFloat? = nil, alignment: Alignment = .center) -> some View

    So, to make the Text leading be aligned to the left, simply:

    Text("entry.titleAlert hajdfg dgfhds fghjds gfhjdsg fhjdsg2")
        .frame(maxWidth: .infinity, alignment: .leading)
        ...