代码之家  ›  专栏  ›  技术社区  ›  TruMan1

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

  •  0
  • TruMan1  · 技术社区  · 6 年前

    我试着模仿下面的截图 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 回复  |  直到 6 年前
        1
  •  0
  •   E.Coms    6 年前

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

    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