如何在工具栏中的图标下添加文字?

时间:2015-06-25 06:40:34

标签: ios swift

我想在工具栏中的图标下添加文字。

现在我可以添加或标题或图像。

我可以说我会有图像并且在文字的图像标签下吗?

我确实在图片的底部添加了标签,但是我怎样才能像def create(self, cr, uid, vals, context=None): ### here you can change the value of the fields vals.update({'field': value}) ## then call the super method return super(class_name, self).create(cr, uid, vals, context=context) 那样使用图片进行分类?

1 个答案:

答案 0 :(得分:0)

首先,您需要创建UIButton的扩展,this post给出解决方案。然后,您可以在UIBarButtonItem

中嵌入UIButton作为自定义视图
extension UIButton {
    func centerLabelVerticallyWithPadding(spacing:CGFloat) {
        // update positioning of image and title
        let imageSize = self.imageView!.frame.size
        self.titleEdgeInsets = UIEdgeInsets(top:0,
            left:-imageSize.width,
            bottom:-(imageSize.height + spacing),
            right:0)
        let titleSize = self.titleLabel!.frame.size
        self.imageEdgeInsets = UIEdgeInsets(top:-(titleSize.height + spacing),
            left:0,
            bottom: 0,
            right:-titleSize.width)

        // reset contentInset, so intrinsicContentSize() is still accurate
        let trueContentSize = CGRectUnion(self.titleLabel!.frame, self.imageView!.frame).size
        let oldContentSize = self.intrinsicContentSize()
        let heightDelta = trueContentSize.height - oldContentSize.height
        let widthDelta = trueContentSize.width - oldContentSize.width
        self.contentEdgeInsets = UIEdgeInsets(top:heightDelta/2.0,
            left:widthDelta/2.0,
            bottom:heightDelta/2.0,
            right:widthDelta/2.0)
    }
}


class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let customButton : UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
        customButton.setImage((UIImage(named: "Image")), forState:UIControlState.Normal)
        customButton.setTitle("Button", forState: UIControlState.Normal)
        customButton.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
        customButton.sizeToFit()
        customButton.centerLabelVerticallyWithPadding(5)
        let customBarButtonItem = UIBarButtonItem(customView: customButton as UIView)
        self.navigationItem.rightBarButtonItem = customBarButtonItem;

    }
}