Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I have achieve a combined line limit for two Text views in a VStack in SwiftUI?

Tags:

swiftui

vstack

I have a design that I want to achieve in SwiftUI, and there are three examples shown below.

enter image description here

It's a VStack that contains an Image, and two Text views.

  1. It should show no more than three lines of text, ie the container view should not grow in height if both Text views would have enough text for two rows
  2. It should not shrink in height when there is only one line of text for each text view.
  3. It should support dynamic font sizes
like image 956
Ben Thomas Avatar asked Oct 16 '25 00:10

Ben Thomas


2 Answers

regarding the idea with the placeholder, you can use native solutions such as .lineLimit(3, reservesSpace: true)

like image 89
miltenkot Avatar answered Oct 17 '25 13:10

miltenkot


The part of the implementation should go like this which will guarantee your conditions I think.

import SwiftUI

struct ContentView: View {
    @State var title = "Title text"
    @State var subTitle = "Subtitle text"
    
    var isSubtitleLarger: Bool {
        subTitle.count > title.count
    }
    
    var body: some View {
        VStack(alignment: .leading) {
            Text(title)
                .lineLimit(isSubtitleLarger ? 1 : 2)
            
            Text(subTitle)
                .lineLimit(isSubtitleLarger ? 2 : 1)
        }
        .frame(minHeight: 150) // Add minimum height to meet minimum size, so that the view doesn't shrink when texts are small 
    }
}

This is important to guarantee there is always 3 lines at max.

like image 42
Mahi Al Jawad Avatar answered Oct 17 '25 14:10

Mahi Al Jawad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!