Search code examples
swiftswiftui

How can I get rid of HStack padding?


I created following struct

private struct Notification: View {
    let notification: NotificationModel
    let onClick: () -> Void
    
    init(
        notification: NotificationModel,
        onClick: @escaping () -> Void
    ) {
        self.notification = notification
        self.onClick = onClick
    }
    
    var body: some View {
        VStack(alignment: .leading) {
            Text(notification.title)
            HStack {
                Text(notification.body)
                if !notification.isRead {
                    Spacer()
                    Circle().frame(width: 6, height: 6)
                }
            }
        }
        .frame(maxWidth: .infinity)
        .onTapGesture(count: 1, perform: onClick)
    }
}

and used it like this

NavigationView {
    List {
        ForEach(model.notifications) { notification in
            Notification(
                notification: notification,
                onClick: { ... }
            )
            .listRowSeparator(.hidden)
        }
    }
    .listStyle(.plain)
    .navigationTitle("screen_notifications_title")
}

Everything looks fine, except for this

enter image description here

As you can see, the space between title and body is different between a read notification and an unread one. I think the issue might be related to the Circle(), but I didn't manage to fix it. How can I do it?


Solution

  • In your Notification View, try using spacing, such as:

       VStack(alignment: .leading, spacing: 10) { // <-- here, adjust
            Text(notification.title).font(.title3)
            HStack {
                Text(notification.body)
                    .font(.subheadline)
                    .lineLimit(bodyLineLimit)
                if !notification.isRead {
                    Spacer()
                    Circle()
                        .frame(width: 6, height: 6)
                        .foregroundColor(.red)
                }
            }
        }
    

    to adjust the space between the Text(notification.title).font(.title3) and the HStack.

    Note, NavigationView is deprecated, you should use NavigationStack