如何在SwiftUI中将占位符文本添加到TextEditor? [英] How to add placeholder text to TextEditor in SwiftUI?

查看:133
本文介绍了如何在SwiftUI中将占位符文本添加到TextEditor?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用SwiftUI的新TextEditor时,您可以直接使用@State修改其内容.但是,我还没有找到一种向其添加占位符文本的方法.现在可行吗?

When using SwiftUI's new TextEditor, you can modify its content directly using a @State. However, I haven't see a way to add a placeholder text to it. Is it doable right now?

我添加了一个Apple在自己的翻译器应用程序中使用过的示例.似乎是多行文本编辑器视图,支持占位符文本.

I added an example that Apple used in their own translator app. Which appears to be a multiple lines text editor view that supports a placeholder text.

推荐答案

这是不可能的,但您可以使用 ZStack .overla y属性.

It is not possible out of the box but you can achieve this effect with ZStack or the .overlay property.

您应该做的是检查拥有您所在州的财产.如果为,则显示您的占位符文本.如果不是,则显示输入的文本.

What you should do is check the property holding your state. If it is empty display your placeholder text. If it's not then display the inputted text instead.

这是一个代码示例:

ZStack(alignment: .leading) {
    if email.isEmpty {
        Text(Translation.email)
            .font(.custom("Helvetica", size: 24))
            .padding(.all)
    }
    
    TextEditor(text: $email)
        .font(.custom("Helvetica", size: 24))
        .padding(.all)
}

注意:我特意将.font和.padding样式留给您,以使其在TextEditor和Text上均应匹配.

考虑到Legolas Wang的评论中提到的两个问题是如何处理对齐和不透明度问题:

Having in mind the two problems mentioned in Legolas Wang's comment here is how the alignment and opacity issues could be handled:

  • 要使Text从视图的左侧开始,只需将其包装在HStack中,并在其后立即添加Spacer,如下所示:
HStack {
   Text("Some placeholder text")
   Spacer()
}

  • 为了解决不透明问题,您可以使用条件不透明性-最简单的方法是使用像这样的三元运算符:
  • TextEditor(text: stringProperty)        
            .opacity(stringProperty.isEmpty ? 0.25 : 1)
    

    当然,在增加对TextEditor的支持之前,此解决方案只是一个愚蠢的解决方法.

    Of course this solution is just a silly workaround until support gets added for TextEditors.

    这篇关于如何在SwiftUI中将占位符文本添加到TextEditor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆