【问题标题】:CATextLayer is ignoring NSMutableParagraphStyleCATextLayer 忽略 NSMutableParagraphStyle
【发布时间】:2016-07-06 05:37:04
【问题描述】:

我想用NSMutableAttributedStringCATextLayer上用文字绘制文字。我尝试通过[attrString setAttributes:attributes range:range]; 将属性设置为NSMutableAttributedString 的类似字体和字体颜色,但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
}

是不是我做错了什么?

【问题讨论】:

    标签: catextlayer


    【解决方案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
            }
        }
    

    【讨论】:

    • 这个答案在 2019 年和 iOS 13 中仍然有效……
    猜你喜欢
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多