'SwiftUI how to align the view‘s leading to the most super view’s leading?
I’m new to SwiftUI and I’m making a widget. The default code included a text view which is both x-centered and y-centered in the super view(which I don’t know if there’s the same concept in SwiftUI). This is my code:
struct WidgetEntryView : View {
var entry: Provider.Entry
var body: some View {
VStack(alignment: .leading){
Text(Date(), style: .time)
.padding(.leading)
}
}
}
I want to align the view’s leading to the super view’s leading instead of positioning the text in the center. So I tried to add a padding to the text’s leading, strangely, it seems that the text view is not a direct subview of the superview, it is positioned in a invisible centered view instead, since I end up with having a text view that slightly deviate the center, looks like this:
This is what I want:
I tried the position method and it was the only one worked, not perfectly though, since it is based on the center point.
I’m looking for a better solution.
Solution 1:[1]
Here is a Playground that gives an example of a view that looks like your picture:
import UIKit
import SwiftUI
import PlaygroundSupport
struct ViewWithText : View {
var body : some View {
HStack {
Text("Here")
.background(Color.yellow)
}
.frame(width: 320, height: 480, alignment: .leading)
.background(Color.gray)
}
}
let hostingController = UIHostingController(rootView: ViewWithText())
PlaygroundSupport.PlaygroundPage.current.liveView = hostingController
Solution 2:[2]
With simple padding and background you can see why it does not work for you as you want.
VStack(alignment: .leading){
Text(Date(), style: .time)
.padding(.leading)
.background(.yellow)
}
.padding()
.background(Color.gray)
The base size of the VStack
is the same as the size of it's children. Solution would be to increase the size of the VStack
or the size of the Text
In widget I suggest to set the parent (V)Stack
's size (maxWidth
) as big as it can get (.infinity
) :
VStack(alignment: .leading){
Text(Date(), style: .time)
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding()
Btw setting padding(.leading)
is causing the "text view that slightly deviate the center" as this added a base padding to the left size of the Text. It just increases the width of the text, but still not fully to the available width.
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 | Scott Thompson |
Solution 2 | petin |