Search code examples
swiftnsattributedstring

Xcode Swift - Attributed Text won't work with font attributes


The compiler keeps throwing this error: "Type of expression is ambiguous without more context". It's throwing it on the: let textFontAttributes = [NSAttributedString. Could someone point me in the right direction. Thanks.

    let textRect = CGRect(x: 50, y: 60, width: 56, height: 35)
    let textTextContent = String(globalWorkoutCount) + " / 7"
    let textStyle = NSMutableParagraphStyle()
    textStyle.alignment = .center
    let textFontAttributes = [NSAttributedString: UIFont(name: "Avenir-Medium", size: 24)!, NSForegroundColorAttributeName: UIColor.white, NSMutableParagraphStyle: textStyle]

    let textTextHeight: CGFloat = textTextContent.boundingRect(with: CGSize(width: textRect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: textFontAttributes, context: nil).height
    context.saveGState()
    context.clip(to: textRect)
    textTextContent.draw(in: CGRect(x: textRect.minX, y: textRect.minY + (textRect.height - textTextHeight) / 2, width: textRect.width, height: textTextHeight), withAttributes: textFontAttributes)
    context.restoreGState()

Solution

  • Change NSAttributedString to NSFontAttributeName and NSMutableParagraphStyle to NSParagraphStyleAttributeName and it should work.

    Here is what it should end up looking like:

    let textFontAttributes = [NSFontAttributeName: UIFont(name: "Avenir-Medium", size: 24)!, NSForegroundColorAttributeName: UIColor.white, NSParagraphStyleAttributeName: textStyle]