How to wrap Text around some view in a HStack?

对着背影说爱祢 提交于 2021-01-01 07:14:24

问题


I wanted to ask if following scenario would be possible and if yes how I could approach the problem. The following code produces the attached image:

HStack(alignment: .firstTextBaseline) {
  ZStack {
      RoundedRectangle(cornerRadius: 5)
      .foregroundColor(Color(UIColor.secondarySystemFill))
    
      Text("Test")
      .clipShape(RoundedRectangle(cornerRadius: 5))
      .foregroundColor(.secondary)
      .layoutPriority(1)
      .padding(.all, 5)
  }

  Text("This is a very long message with more words than one line can handle bla blabla blablabl")
}

Now in order to save more space I would like to have the next lines move to the left like so:

I have considered following approaches but none got me very far:

  1. Using Swift UIs Text() + Text() instead of the HStack. This would not work as this method does not allow background colors (a .background() would converter the Text() to some View and therefore I can't combine it with another Text()). I could only change the .foregroundColor.
  2. Maybe I could somehow write a UIKit wrapper for a UILabel with NSAttributedString. I don't like this method very much though, as changing background colors with NSAttributedString isn't a very good solution either.
  3. Use a ZStack and maybe somehow throw a .clipShape() onto the longer right hand Text() so that it moves a little more to the right. This approach is also quite hacky since I don't quite know how to calculate the length of the first string so that I could move the second string.

Either I am missing something or this just isn't something that you could do in Swift UI or UIKit.

来源:https://stackoverflow.com/questions/62601163/how-to-wrap-text-around-some-view-in-a-hstack

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!