如何快速将一串逗号值转换为项目符号列表?

时间:2019-08-22 21:16:08

标签: swift

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

// 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"])

-谢谢大家

1 个答案:

答案 0 :(得分:1)

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

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)