Swift - Drawing text with drawInRect:withAttributes:

前端 未结 5 607
自闭症患者
自闭症患者 2020-12-14 08:15

I have strange problem with Xcode 6.1 GM.

let text: NSString = \"A\"
let font = NSFont(name: \"Helvetica Bold\", size: 14.0)

let textRect: NSRect = NSMakeRe         


        
相关标签:
5条回答
  • 2020-12-14 09:07

    In XCode 12, Swift 5.3. i was not able to find the draw method for String object. After i manually cast to NSString, it worked for me.

    let text: String = "XXX"
    (text as NSString).draw(in: rect withAttributes: attributes)
    
    0 讨论(0)
  • 2020-12-14 09:09

    This is also another option.

    let textFontAttributes = [
        NSFontAttributeName : font!,
        NSForegroundColorAttributeName: textColor,
        NSParagraphStyleAttributeName: textStyle
    ]
    
    0 讨论(0)
  • 2020-12-14 09:11

    The problem is that font is optional because the convenience contructors now return optional values, so font needs to be unwrapped to be a value in your dictionary:

    if let actualFont = font {
        let textFontAttributes = [
            NSFontAttributeName: actualFont,
            NSForegroundColorAttributeName: textColor,
            NSParagraphStyleAttributeName: textStyle
        ]
    
        text.drawInRect(NSOffsetRect(textRect, 0, 1), withAttributes: textFontAttributes)
    }
    
    0 讨论(0)
  • 2020-12-14 09:11

    I have this piece of code in my app which works without problems:

        var textAttributes: [String: AnyObject] = [
            NSForegroundColorAttributeName : UIColor(white: 1.0, alpha: 1.0).CGColor,
            NSFontAttributeName : UIFont.systemFontOfSize(17)
        ]
    
    0 讨论(0)
  • 2020-12-14 09:17

    In Swift 4

        let attributeDict: [NSAttributedString.Key : Any] = [
            .font: font!,
            .foregroundColor: textColor,
            .paragraphStyle: textStyle,
        ]
    
        text.draw(in: rect, withAttributes: attributeDict)
    
    0 讨论(0)
提交回复
热议问题