首页 > 解决方案 > 如何快速将一串逗号值转换为项目符号列表?

问题描述

我正在使用一个将数组作为参数的函数,但问题是我有一串逗号值需要用作参数。

// comma values in a string
let comment = "Examples of things, Another thing, More things" 

// the bulletPoint function that takes an array.
func bulletPointList(strings: [String]) -> NSAttributedString {
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.headIndent = 15
    paragraphStyle.minimumLineHeight = 22
    paragraphStyle.maximumLineHeight = 22
    paragraphStyle.tabStops = [NSTextTab(textAlignment: .left, location: 15)]

    let stringAttributes = [
        NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15),
        NSAttributedString.Key.foregroundColor: UIColor.white,
        NSAttributedString.Key.paragraphStyle: paragraphStyle
    ]

    let string = strings.map({ "•\t\($0)" }).joined(separator: "\n")

    return NSAttributedString(string: string,
                              attributes: stringAttributes)
}

我应该先将注释字符串转换为数组吗?

//The function looks like this called
label.numberOfLines = 0

label.attributedText = bulletPointList(strings: ["Examples of things", "Another thing", "More things"])

-谢谢大家

标签: swift

解决方案


如果我的理解是正确的,你可以使用下面的代码来获取字符串数组。

let comment = "Examples of things, Another thing, More things"


let stringArray = comment.split(separator: ",").map{String($0)}
label.attributedText = bulletPointList(strings: stringArray)

//or

let stringArray1 = comment.components(separatedBy: ",")
label.attributedText = bulletPointList(strings: stringArray1)

推荐阅读