Reputation: 1566
I'm currently trying to align the person image bottom trailing to the bottom edge of the image in a SwiftUI View.
Code:-
struct AddSecondImageOnSameImage: View {
@State var image = Image(systemName: "person.circle.fill")
var body: some View {
VStack{
self.image
.renderingMode(.original)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 100, height: 100)
.clipShape(Circle())
.padding(1)
.overlay(Circle()
.frame(width: 20, height:20)
.foregroundColor(Color.init(UIColor.init(displayP3Red: 255/255, green: 92/255, blue: 210/255, alpha: 1.0))),alignment: .bottomTrailing)
}
}
}
Output:-
]
Want to achieve:-
Can someone please explain to me how to align the person image bottom trailing to the bottom edge of the image in a SwiftUI View. I've tried to implement by above but no results yet. Any help would be greatly appreciated. Thanks in advance.
Upvotes: 1
Views: 2140
Reputation: 27
By using a Z-Stack and defining the frame, you can align the views inside by manipulating their frame using .infinity
and setting the alignment to the desired outcome. For example in your scenario:
import SwiftUI
struct SampleView: View {
@State var image = Image(systemName: "person.circle.fill")
var body: some View {
ZStack {
self.image
.renderingMode(.original)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 100, height: 100, alignment: .center)
.clipShape(Circle())
.padding(1)
Circle()
.frame(width: 20, height:20)
.foregroundColor(.green)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing)
}
.frame(width: 100, height: 100)
}
}
There are several ways to implement it but setting the frame and the alignment is required. Avoid using offset constants since this would not work the same everywhere, for example, in responsive resizing.
Upvotes: 0
Reputation: 15055
Use ZStack
instead of .overlay()
The ZStack assigns each successive child view a higher z-axis value than the one before it, meaning later children appear “on top” of earlier ones.
struct AddSecondImageOnSameImage: View {
@State var image = Image(systemName: "person.circle.fill")
var body: some View {
ZStack(alignment: .bottomTrailing) {
self.image
.renderingMode(.original)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 100, height: 100)
.clipShape(Circle())
.padding(1)
Circle()
.frame(width: 20, height:20)
.foregroundColor(Color.init(UIColor.init(displayP3Red: 255/255, green: 92/255, blue: 210/255, alpha: 1.0)))
.offset(x: -5, y: -5)
}
}
}
You may need to adjust the offset.
Upvotes: 4