SwiftUI - inline style text background color that fits to the width of multi line text SwiftUI

452 Views Asked by At

I am trying to create a background text color that tracks to the width of each line of multi line text. See image below:

Line text view

I have only been able to get a basic box background color using .background(Color.black) it gives a background to the entire text box. The desired effect is to give the background only to the end of each line of text.

1

There are 1 best solutions below

0
On

I only know how to solve this in PHP/CSS. First, put the text into a variable. then replace all spaces through the div tags. then add the CSS for the div. and that's it:

!Important! be sure that at the beginning and the is no space and in the middle of the text are not enter space

Here my code example:

<style>
    .divs{
        background-color: black;
        color: white;
        margin: 5px 0px 5px 0px;/* space from top and bottom*/
        padding-left: 5px;/* word spacing */
        float: left;/* Importand to stick them together */
        font-size: 20pt;
    }
</style>
<div>
<?php
  $yourtext = 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.';
  echo "<div class='divs'>".str_replace(" ", "</div> <div class='divs'>", $yourtext)."</div>";
?>
</div>

But I'm sure that the same method is possible with SwiftUI by just looping the text and replace the space

--> just search for text-replacing in SwiftUI and you will find what you need