【发布时间】:2015-06-25 06:40:33
【问题描述】:
我想在工具栏的图标下添加一个文本。
现在我可以添加或添加标题或图像。
我可以让我有图像和文字的图像标签下吗?
我确实在图像底部添加了标签,但是我如何像使用 Flexible Space Bar Button Item 的图像那样处理它?
【问题讨论】:
我想在工具栏的图标下添加一个文本。
现在我可以添加或添加标题或图像。
我可以让我有图像和文字的图像标签下吗?
我确实在图像底部添加了标签,但是我如何像使用 Flexible Space Bar Button Item 的图像那样处理它?
【问题讨论】:
首先你需要创建一个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;
}
}
【讨论】: