仅使用属性字符串的标签列表

时间:2018-09-12 15:48:46

标签: ios uilabel nsattributedstring

我正在尝试使用NSAttributedString而不是完整的UICollectionView来模仿下面的屏幕截图。

enter image description here

我快到了,但是我无法获得白线间隔和换行符: enter image description here

这是我的代码:

let attributedText = myList.reduce(into: NSMutableAttributedString()) { result, next in
    let text = NSMutableAttributedString(string: "   ")
    text.append(NSMutableAttributedString(string: next))
    text.append(NSMutableAttributedString(string: "   "))
    text.addAttributes(
        [
            .font: UIFont.systemFont(ofSize: 12),
            .foregroundColor: UIColor.darkGrey,
            .backgroundColor: UIColor.lightGray
        ],
        range: NSRange(location: 0, length: text.length)
    )

    result.append(text)

    guard myList.last != next else { return }
    result.append(NSMutableAttributedString(string: "  "))
}

attributedText.addAttributes(
    [
        .paragraphStyle: NSMutableParagraphStyle().with {
            $0.alignment = .center
            $0.lineHeightMultiple = 2
            $0.lineSpacing = 12
        }
    ],
    range: NSRange(location: 0, length: attributedText.length)
)

attributedText.append(NSMutableAttributedString(string: "\n"))

myLabel.attributedText = attributedText

是否存在可以处理该属性以使其看起来像第一个屏幕截图的属性?

1 个答案:

答案 0 :(得分:0)

这是我的回答,其中快速手动修复了“ Meal”位置。您可能不需要它,取决于您的标签布局。

let attributedText = myList.reduce(into: NSMutableAttributedString()) { result, next in



        let whitespace = NSMutableAttributedString(string: "   ")
        whitespace.addAttributes(
            [
                .font: UIFont.systemFont(ofSize: 12),
                .foregroundColor: UIColor.darkGray,
                .backgroundColor: UIColor.white
            ],
            range: NSRange(location: 0, length: whitespace.length)
        )


        let text = NSMutableAttributedString(string:  next)

        text.addAttributes(
            [
                .font: UIFont.systemFont(ofSize: 12),
                .foregroundColor: UIColor.darkGray,
                .backgroundColor: UIColor.lightGray
            ],
            range: NSRange(location: 0, length: text.length)
        )


        result.append(whitespace)
        if(next.hasPrefix("Meal")){
             result.append(whitespace)

        }
        result.append(text)
           result.append(whitespace)
        guard myList.last != next else { return }
        result.append(NSMutableAttributedString(string: "  "))
    }

enter image description here