UIBarButtonItem标题偏移量

时间:2014-09-03 02:06:17

标签: ios swift uikit uibarbuttonitem

我试图在UIBarButtonItem标题中使用unicode符号,但更改标签大小使其垂直位置过高,显然偏离中心。

ergh

目前正在使用的代码:

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

我尝试添加偏移量,但它似乎没有做任何事情。

editButton.setTitlePositionAdjustment(UIOffsetMake(0, -10.0), forBarMetrics: UIBarMetrics.Default)

1 个答案:

答案 0 :(得分:8)

我遇到了类似的问题,到目前为止我发现的最佳选择是从文本创建UIImage(使用白色文本颜色),然后使用图像创建我的UIBarButtonItem。白色被标准色调取代,并使图像垂直居中。

我找到了在this SO question的答案中将文字转换为图片的方法。然后我使用此代码(在Swift中)设置UIBarButtonItem:

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");

注意:imageFromText函数可以在上面引用的SO答案中找到,但是为了方便起见,我将在这里包含它(以及一个相关的函数):

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
}