2

I have the following code:

extension HorizontalAlignment {
    private enum TestWidth: AlignmentID {
        static func defaultValue(in context: ViewDimensions) -> CGFloat {
            return 40
        }
    }
    static let testWidth = HorizontalAlignment(TestWidth.self)
}


struct AGTView: View {
    
    var body: some View {
        
        VStack(alignment: .testWidth) {
            
            HStack {
                
                Image(systemName: "airplane.circle")
                    .font(Font.system(size: 40, weight: .regular))
                    .foregroundColor(.white)
                
                Text("testing")
                    .alignmentGuide(.testWidth, computeValue: { d in d[HorizontalAlignment.leading] })
                    .foregroundColor(.white)
                    .border(.yellow)
                
                Spacer()
                
            }
            .border(.red)
            
            Text("some text to align with the leading of `testing` text 000000 some text to align with the leading of `testing` text\n\nsome text to align with the leading of `testing` text")
                .font(Font.system(size: 10, weight: .regular))
                .lineLimit(nil)
                .multilineTextAlignment(.leading)
                .alignmentGuide(.testWidth, computeValue: { d in d[HorizontalAlignment.leading] })
                .foregroundColor(.white)
                .border(.pink)
            
            Spacer()
            
        }
        .frame(height: 100)
        .frame(width: 200)
        .border(.green)
        .background(.black)
        
    }
    
}

It draws this:

enter image description here

I am trying to understand how to make the content of the VStack stay inside of the VStack frame when using custom Horizontal alignment guides. Int this case I am using the testWidth, and although the content inside the VStack gets aligned like I want it to be aligned, it bleeds out of the VStack.

I want to align the content inside the VStack, while staying within the 200 width I set for the VStack frame so the VStack's content doesn't bleed out.

I am probably thinking about this wrong, but, put it simply, I want the VStack to be placed on screen like it is, with the 200x100 frame I set, and its content aligned but not out of VStack bounds.

How do I achieve that in SwiftUI?

zumzum
  • 17,984
  • 26
  • 111
  • 172
  • 1
    It is expected behavior, views are constructed at first and only then aligned. Alignment does not change own view's frame. You might find helpful this https://stackoverflow.com/a/62451599/12299030 – Asperi Dec 11 '21 at 06:18
  • makes sense. My UIKit habits.... breaking them one at the time I guess. – zumzum Dec 13 '21 at 03:14
  • @zumzum, did you figure it out? That other question didn't really help me, I'm afraid. – FreeNickname Dec 23 '22 at 19:30

0 Answers0