简体   繁体   中英

Swift UI Label with space between lines + dynamic line width

Currently, I have. Current UI Label

However, I would like it to have space between the lines so the background shows and a background color that has a dynamic width for each line, something similar to

Desired Label Look

I have tried converting my label into a text view, and using a custom class. This does not get the desired outcome. When a new cell is created, it uses the following code.

cell.label.backgroundColor = UIColor.white
        return cell

So, how could I get the text to get spaces between the lines as in the picture with the background showing through, and the width for each line based off the text as in the picture?

Are you sure you've uploaded the images you intended to? Your Desired Label Look does not have a background colour that follows the text with like you describe.

Here's an example to get you going:

let string = "Hello\n\nIs it me you're\n\nlooking for"
var attributedString = NSMutableAttributedString(string:string)

string.enumerateLines { (line, stuff) in
    guard let range = string.range(of: line) else { return }
    let nsRange = NSRange(range, in: line)
    attributedString.addAttribute(.backgroundColor,
                                  value: UIColor.red,
                                  range: nsRange)
}

Here I am making each line of the string red individually to get the effect you describe.

I used double line breaks to achieve the separation, as I don't think it's possible to simply get the separated line effect with a single NSAttributedString .

This results in:

在此处输入图片说明

.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM