Search code examples
iosswiftcgrect

drawInRect text alignment using Swift


I am trying to put some text on top of an image that would be in the center of a CGRect which would be on top of that image. Here is a bit of code:

        let textColor: UIColor = UIColor.whiteColor()
        let textFont: UIFont = UIFont(name: "Helvetica Bold", size: 17
            )!
        let textAlignment = NSTextAlignment.Center

        let textFontAttributes = [
            NSFontAttributeName: textFont,
            NSForegroundColorAttributeName: textColor,
            NSTextAlignment: textAlignment
            ]

        myString.drawInRect(rect, withAttributes: textFontAttributes)

The problem is in the text alignment. When I write it like this I get an error:

Type of expression is ambiguous without more context

When I set key and value types to [String : AnyObject] the compiler complains again:

Cannot convert value of type 'NSTextAlignment.Type' to expected dictionary key type 'String'

Which I understand. I researched this for like two hours and haven't found any up to date solution and not single one how cloud one write this using Swift.


Solution

  • NSTextAlignment isn't a valid key. Note how the other keys end in Name. See the docs for NSFontAttributeName and NSForegroundColorAttributeName to see the list of valid keys.

    Instead of NSTextAlignment you need to use NSParagraphStyleAttributeName which requires that you create an instance of NSParagraphStyle. That is where you set the alignment to .Center.

    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = .Center