CATextLayer игнорирует NSMutableParagraphStyle

Я хочу использовать NSMutableAttributedString для рисования текста на CATextLayer с текстом. Я пытаюсь установить такие атрибуты, как шрифт и цвет шрифта от NSMutableAttributedString до [attrString setAttributes:attributes range:range];, но все атрибуты в NSMutableParagraphStyle игнорируются.

let str = "I want to use NSMutableAttributedString to draw the text on the CATextLayer with the text. I try set attributes to the like font and fontcolor of the NSMutableAttributedString through the [attrString setAttributes:attributes range:range]; but all attributes in the NSMutableParagraphStyle are ignored."
    let att = NSMutableAttributedString(string: str)
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineSpacing = 12
    att.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, str.characters.count))
let contentLayer = initTextLayer("", andFontSize: 11)
    contentLayer.string = att
    contentLayer.frame = CGRect(x: 30 * AUTOSIZESCALEX, y: CGRectGetMaxY(titleLayer.frame) + 15 * AUTOSIZESCALEY, width: SCREEN_WIDTH - 60 * AUTOSIZESCALEX, height: 200 * AUTOSIZESCALEY)
    self.contentView.layer.addSublayer(contentLayer)

func initTextLayer(title: String, andFontSize size: CGFloat) -> CATextLayer{
    let textLayer = CATextLayer()
    textLayer.foregroundColor = UIColor(hexString: "333333").CGColor
    textLayer.string = title
    textLayer.alignmentMode = kCAAlignmentLeft
    textLayer.contentsScale = UIScreen.mainScreen().scale
    textLayer.shouldRasterize = false
    textLayer.wrapped = true
    textLayer.fontSize = size  * AUTOSIZESCALEY
    return textLayer
}

есть что-то, что я делаю неправильно?


person Q.Chuang    schedule 06.03.2016    source источник


Ответы (1)


У меня была аналогичная проблема, и я использовал это:

    // Set text alignment. Apparently CATextLayer doesn't use value in NSAttributedString.
    if let style = text.attribute(NSParagraphStyleAttributeName, atIndex: 0, effectiveRange: nil) as? NSParagraphStyle {
        switch style.alignment {
        case .Center:
            textLayer.alignmentMode = kCAAlignmentCenter
        case .Left:
            textLayer.alignmentMode = kCAAlignmentLeft
        case .Right:
            textLayer.alignmentMode = kCAAlignmentRight
        default:
            break
        }
    }
person LenK    schedule 05.07.2016
comment
Этот ответ по-прежнему актуален в 2019 году и iOS 13… - person wider-spider; 04.09.2019