【问题标题】:Tag list using attributed string only仅使用属性字符串的标记列表
【发布时间】:2018-09-12 15:48:46
【问题描述】:

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

我快到了,但我无法正确设置白行间距和换行符:

这是我的代码:

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

是否有属性可以处理这个问题,使其看起来像第一个屏幕截图?

【问题讨论】:

标签: ios uilabel nsattributedstring


【解决方案1】:

这是我在“用餐”位置快速手动修复的答案。您可能不需要它,具体取决于您的标签布局。

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: "  "))
    }

【讨论】:

    猜你喜欢
    • 2020-04-29
    • 2014-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多