【问题标题】:SwiftUI: How-to append view to ending of multiline text?SwiftUI:如何将视图附加到多行文本的结尾?
【发布时间】:2020-12-02 14:46:42
【问题描述】:

当前

我有类似以下内容:

带有徽章的短文本:

使用 HStack atm 很简单:

HStack {
    Text("Lorem ipsum dolor sit amet.")
        .font(.title2)
    Text("foo")
        .font(.system(size: 14, weight: .bold))
        .foregroundColor(.white)
        .padding(.horizontal, 4)
        .padding(.vertical, 2)
        .background(Color.red)
        .cornerRadius(5)
}

我的问题是正文是多行的,如果换行,它看起来像这样:

带有徽章的更大的多行文本:

目标

但我的目标是 foo 标记始终显示在正文的最后一个单词之后,应该如下所示:

目标:Text + Text 之类的解决方案:

换句话说,我想要与使用 SwiftUI 文本 (Text() + Text()) 的连接功能相同的行为,但由于徽章的格式,我不能使用它。 background() 之类的格式化修饰符会将返回类型更改为 View,然后 + 运算符不再起作用。

实现我的目标最优雅的解决方案是什么?我宁愿不使用 UIKit。

【问题讨论】:

  • 这个stackoverflow.com/questions/59531122/… 可能会有所帮助。第二个答案。
  • @ezaji 你的意思是第三个答案,自定义 AttributedText 实现?第二个答案,我不能使用 + 运算符,因为背景和填充的东西会改变返回类型,就像我已经描述的那样。
  • 是的,第三个答案更适合您的目的。

标签: swiftui


【解决方案1】:

以下解决方案给出了结果,但徽章将位于行尾。 如果是静态文本,可以使用offset(x: )手动实现。

ZStack(alignment: .bottomTrailing) {
       Text("But my goal is that the foo badge is always displayed after the last word of the main text, which should look like this:")
           .font(.title2)

       Text("foo")
           .font(.system(size: 14, weight: .bold))
           .foregroundColor(.white)
           .padding(.horizontal, 4)
           .padding(.vertical, 2)
           .background(Color.red)
           .cornerRadius(5)
           .alignmentGuide(.bottom) { d in d[.bottom] }
           // .offset(x: 50)
}

【讨论】:

  • 不幸的是,文本是动态的,可能是 1 到 160 个字符之间的所有内容
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-30
  • 2013-11-15
  • 1970-01-01
  • 1970-01-01
  • 2011-09-06
相关资源
最近更新 更多