简体   繁体   English

带有行间距+动态线宽的Swift UI标签

[英]Swift UI Label with space between lines + dynamic line width

Currently, I have. 目前,我有。 Current UI Label 当前UI标签

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 . 我使用双换行符来实现分隔,因为我认为不可能仅使用单个NSAttributedString获得分隔线效果。

This results in: 结果是:

在此处输入图片说明

.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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