how you can create a user profile card using VStack
and HStack
in SwiftUI, along with some styling options:
import SwiftUI
struct UserProfileCard: View {
let profileImage: Image
let userName: String
let userBio: String
var body: some View {
VStack(alignment: .leading, spacing: 10) {
HStack(alignment: .center, spacing: 15) {
profileImage
.resizable()
.scaledToFill()
.frame(width: 80, height: 80)
.clipShape(Circle())
VStack(alignment: .leading) {
Text(userName)
.font(.headline)
.fontWeight(.semibold)
Text(userBio)
.font(.subheadline)
}
}
// Add other elements to the card here if needed (e.g., buttons, social links)
}
.padding() // Add padding around the entire card
.background(Color(.systemGray6)) // Light gray background
.cornerRadius(15) // Rounded corners
}
}
// Example Usage
struct ContentView: View {
var body: some View {
UserProfileCard(
profileImage: Image("profile_photo"), // Replace with your image name
userName: "John Doe",
userBio: "Software Engineer | Coffee Lover | Traveler"
)
}
}
Explanation:
- UserProfileCard View:
- It takes three parameters:
profileImage
,userName
, anduserBio
. - The main
VStack
arranges the profile picture and text information vertically. - The nested
HStack
aligns the profile picture and text horizontally.
- It takes three parameters:
- Profile Image:
profileImage
is loaded and made resizable.scaledToFill()
ensures it fills the frame while maintaining aspect ratio.frame
sets the size of the image.clipShape(Circle())
applies a circular mask to the image.
- User Name and Bio:
VStack
arranges the user’s name and bio text vertically.Text
views display theuserName
anduserBio
.- Different fonts (
headline
,subheadline
) are used for visual hierarchy.
- Styling:
padding()
adds spacing around the card’s content.background(Color(.systemGray6))
sets a light gray background color.cornerRadius(15)
rounds the corners of the card.
- Example Usage (ContentView):
- The
UserProfileCard
view is used inside aContentView
to demonstrate how to create an instance with sample data.
- The
Key Improvements:
- Clear Structure: The use of
VStack
andHStack
creates a well-organized and visually appealing layout. - Alignment: Content is aligned properly using
.leading
(left) alignment for the mainVStack
and.center
alignment for theHStack
. - Spacing: Consistent spacing (
spacing: 10
) is applied between elements for readability. - Customizable: You can easily replace the placeholder image and text with your own data.
- Additional Elements: You can add more elements to the
UserProfileCard
(like buttons or social links) within the mainVStack
.