Reputation: 401
var body: some View {
VStack(alignment: .leading) {
Text("Title")
.bold()
.font(Font.custom("Helvetica Neue", size: 36.0))
...
Button(action: {}){
Text("Create")
.bold()
.font(Font.custom("Helvetica Neue", size: 24.0))
.padding(20)
.foregroundColor(Color.white)
.background(Color.purple)
.cornerRadius(12)
}
}.padding(20)
}
I want different alignments for these two particular elements. Title must have a leading alignment, but on the other hand button is located in the center. Now I set VStack alignment to leading. I'm not familiar with the Swift UI quite well, so the first idea is to use several vertical stacks with different alignments, but I assume it can be done easier. If I add alignment guide to the button, it doesn't work either.
Upvotes: 9
Views: 10461
Reputation: 257711
I would use included HStack
as in demo below
var body: some View {
VStack(alignment: .leading) {
Text("Title")
.bold()
.font(Font.custom("Helvetica Neue", size: 36.0))
HStack {
Spacer()
Button(action: {}){
Text("Create")
.bold()
.font(Font.custom("Helvetica Neue", size: 24.0))
.padding(20)
.foregroundColor(Color.white)
.background(Color.purple)
.cornerRadius(12)
}
Spacer()
}
}.padding(20)
}
Upvotes: 13
Reputation: 3991
One more way is to use a VStack
with center alignment and maxWidth.
VStack(alignment: .leading) {
Text("Title")
.bold()
.font(Font.custom("Helvetica Neue", size: 36.0))
VStack(alignment: .center) {
Button(action: {}){
Text("Create")
.bold()
.font(Font.custom("Helvetica Neue", size: 24.0))
.padding(20)
.foregroundColor(Color.white)
.background(Color.purple)
.cornerRadius(12)
}
}.frame(maxWidth: .infinity)
}.padding(20)
Upvotes: 3
Reputation: 27214
You could use GeometryReader
for this:
A container view that defines its content as a function of its own size and coordinate space.
https://developer.apple.com/documentation/swiftui/geometryreader
GeometryReader { geometry in
VStack(alignment: .leading) {
Text("Title")
.bold()
.font(Font.custom("Helvetica Neue", size: 36.0))
Button(action: {
}) {
Text("Create")
.bold()
.font(Font.custom("Helvetica Neue", size: 24.0))
.padding(20)
.foregroundColor(Color.white)
.background(Color.purple)
.cornerRadius(12)
.frame(width: geometry.size.width / 2, height: geometry.size.height / 2, alignment: .center)
}
}.padding(20)
}
Upvotes: 3