'Prevent overflow of Element in ZStack SwiftUI

I have an arrangement like this for a Horizontal Progress bar in SwiftUI

    ZStack {
    // UI Content
    HStack{
    Text("")
    .frame (width:300)
    }
}

The problem is text will move outside the ZStack when it is at the extreme right or left.

This is what I am trying to achieve (2nd image)

Problem

Any solution to achieve this?



Solution 1:[1]

I solved this solution using the alignment property. Idk whether this is the correct solution or a workaround.

First I made the Stack that contains the text to take the entire width of its parent.

Since the parent element was made using a ForEach, the text will be only displayed in some indices of List.

and I created a function like this

func textAlignment (currentIndex: int, totalIndex:Int) -> Alignment {

if (currentIndex == 0){
return Alignment.leading
}
if (currentIndex == totalIndex-1){
return Alignment.trailing
}
return Alignment.center
}

and I added this to Text stack using .frame(alignment: textAlignment ()) property.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jun53