Список тегов с использованием только приписанной строки - PullRequest
0 голосов
/ 12 сентября 2018

Я пытаюсь имитировать скриншот ниже, используя 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 голосов
/ 12 сентября 2018

Это мой ответ с быстрым ручным исправлением в позиции «Питание». Вам может не понадобиться, это зависит от вашего лейбла.

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

...