【问题标题】:How to add a text under the icon in toolbar?如何在工具栏中的图标下添加文本?
【发布时间】:2015-06-25 06:40:33
【问题描述】:

我想在工具栏的图标下添加一个文本。

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

我可以让我有图像和文字的图像标签下吗?

我确实在图像底部添加了标签,但是我如何像使用 Flexible Space Bar Button Item 的图像那样处理它?

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    首先你需要创建一个UIButton的扩展,this post给出解决方案。然后,您可以将 UIButton 作为自定义视图嵌入到 UIBarButtonItem

    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;
    
        }
    }
    

    【讨论】:

    • 这应该被标记为一个接受的答案。一旦我将标题大小设置为 10 pt 字体并将填充设置为 0,它对我来说非常有用 - 尽管这可能是由于我的图像和条形高度。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-15
    • 1970-01-01
    相关资源
    最近更新 更多