Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIBarButtonItem Title Offset

I'm trying to use a unicode symbol in a UIBarButtonItem title, but changing the label size makes it too high vertically, and it is obviously off center.

ergh

Code currently being used:

let fontDict = [NSFontAttributeName: UIFont.systemFontOfSize(30.0)]
editButton.title = "✎"
editButton.setTitleTextAttributes(fontDict, forState: UIControlState.Normal)

I've tried adding an offset, but it doesn't seem to do anything.

editButton.setTitlePositionAdjustment(UIOffsetMake(0, -10.0), forBarMetrics: UIBarMetrics.Default)
like image 984
Tillson Avatar asked Sep 03 '14 02:09

Tillson


1 Answers

I had a similar issue, and the best option I found so far was to create a UIImage from the text (using a white text color) and then create my UIBarButtonItem using the image. The white color is replaced with the standard tint and it centers the image vertically pretty well.

I found the method for converting text to an image in answers to this SO question. I then setup the UIBarButtonItem using this code (in Swift):

let settingsImage = imageFromText("\u{2699}", font: UIFont(name: "Helvetica", size: 34.0)!, maxWidth: 1000, color:UIColor.whiteColor());
let settingsButton = UIBarButtonItem(image: settingsImage, style: UIBarButtonItemStyle.Plain, target: self, action: "showSettings");

NOTE: the imageFromText function is found in the SO answers referenced above , but I'll include it (and a related function) here for convenience using swift:

class func sizeOfAttributeString(str: NSAttributedString, maxWidth: CGFloat) -> CGSize {
    let size = str.boundingRectWithSize(CGSizeMake(maxWidth, 1000), options:(NSStringDrawingOptions.UsesLineFragmentOrigin), context:nil).size
    return size
}

class func imageFromText(text:NSString, font:UIFont, maxWidth:CGFloat, color:UIColor) -> UIImage
{
    let paragraph = NSMutableParagraphStyle()
    paragraph.lineBreakMode = NSLineBreakMode.ByWordWrapping
    paragraph.alignment = .Center // potentially this can be an input param too, but i guess in most use cases we want center align

    let attributedString = NSAttributedString(string: text, attributes: [NSFontAttributeName: font, NSForegroundColorAttributeName: color, NSParagraphStyleAttributeName:paragraph])

    let size = sizeOfAttributeString(attributedString, maxWidth: maxWidth)
    UIGraphicsBeginImageContextWithOptions(size, false , 0.0)
    attributedString.drawInRect(CGRectMake(0, 0, size.width, size.height))
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
}
like image 196
FTLPhysicsGuy Avatar answered Nov 19 '22 23:11

FTLPhysicsGuy