简体   繁体   中英

SwiftUI: how to set a greater than or equal constraint like UIKit's AutoLayout?

In a UIKit project, I had a constraint like this in one view:

在此处输入图片说明

Here is the result:

在此处输入图片说明

I would like to do the same in SwiftUI, so I tried this:

var body: some View {
    ZStack(alignment: .trailing) {
        Style.Color.blue
            .cornerRadius(17)
        Text(text)
            .foregroundColor(.white)
            .padding(.horizontal, 11)
            .padding(.vertical, 8)
            .lineLimit(nil)
    }
}

I'm getting this result:

在此处输入图片说明

I have no idea how I can do the same than in UIKit, to apply a greather than or equal leading constraint to the blue view. Also, as you can see, on the single line bubble the blue view doesn't stick to the text label, but instead goes to the leading part of the screen. How can I solve this?

Thank you for your help

Here is a possible solution:

struct ItemView: View {
    let text: String

    var body: some View {
        Text(text)
            .foregroundColor(.white)
            .lineLimit(nil)
            .padding(10)
            .background(Color.blue)
            .cornerRadius(17)
    }
}
struct ContentView: View {
    let texts = ["Short text", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."]
    
    var body: some View {
        ZStack(alignment: .trailing) {
            Color.clear
            VStack {
                ForEach(texts, id: \.self) { text in
                    HStack {
                        Spacer()
                        ItemView(text: text)
                    }
                    .padding(.horizontal, 11)
                    .padding(.vertical, 8)
                }
            }
        }
    }
}

Note that instead of \\.self in ForEach(texts, id: \\.self) you may want to provide a way to identify texts (if they can be non-unique).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM