Home > Software engineering >  How do I pin the Text to the very top of the UITextView?
How do I pin the Text to the very top of the UITextView?

Time:09-23

I have a custom UITextView that stretches based on the text entered by the user.
Everything looks good in the first image:

But as soon as I write some text, my placeholder is shifted down, due to .offset:

Code snippet:

VStack (alignment: .leading) {
    VStack {
        DynamicTextField(object: dynamicSize, text: $text, state: $state, placeholder: placeholder)
            .frame(height: self.dynamicSize.size < 100 ? self.dynamicSize.size : 100)
            .padding(.top, isHideHolder ? 15 : 0)
            .background(
                Text("placeholder")
                    .scaleEffect(isHideHolder ? 0.8: 1)
                    .offset(x: isHideHolder ? -14 : 0, y: isHideHolder ? -22 : 0)
                    .foregroundColor(.gray)
                ,
                alignment: .leading
            )
    }
    .padding()
    .background(Color.white)
    .cornerRadius(12)
}       

Is it possible to somehow fix this text so that it does not move? Is there a workaround for my solution? Thanks in advance for the tip!

CodePudding user response:

I think only moving the Text out of the VStack will help here:

VStack (alignment: .leading) {
            VStack(alignment: .leading) {
                if isHideHolder {
                    Text(placeholder)
                        .foregroundColor(.gray.opacity(0.5))
                        .padding(.horizontal, 4)
                }
                DynamicTextField(object: dynamicSize, text: $text, state: $state, placeholder: placeholder)
                    .frame(height: self.dynamicSize.size < 100 ? self.dynamicSize.size : 100)
                    .background(
                        Text("placeholder")
                            .scaleEffect(isHideHolder ? 0.8: 1)
                            .foregroundColor(.gray)
                        ,
                        alignment: .leading
                    )
            }
            .padding()
            .background(Color.white)
            .cornerRadius(12)

If I understand correctly what you mean.

  • Related