[英]StackView - center buttons with text below image
I am using this class for center text below icon for UIButton
: 我正在使用此类用于UIButton
图标下面的中心文本:
@IBDesignable
class TopIconButton: UIButton {
override func layoutSubviews() {
super.layoutSubviews()
let kTextTopPadding:CGFloat = 3.0;
var titleLabelFrame = self.titleLabel!.frame;
let labelSize = titleLabel!.sizeThatFits(CGSize(width: self.contentRect(forBounds: self.bounds).width, height: CGFloat.greatestFiniteMagnitude))
var imageFrame = self.imageView!.frame;
let fitBoxSize = CGSize(width: max(imageFrame.size.width, labelSize.width), height: labelSize.height + kTextTopPadding + imageFrame.size.height)
let fitBoxRect = self.bounds.insetBy(dx: (self.bounds.size.width - fitBoxSize.width)/2, dy: (self.bounds.size.height - fitBoxSize.height) / 2)
imageFrame.origin.y = fitBoxRect.origin.y
imageFrame.origin.x = fitBoxRect.midX - (imageFrame.size.width/2)
self.imageView!.frame = imageFrame;
// Adjust the label size to fit the text, and move it below the image
titleLabelFrame.size.width = labelSize.width
titleLabelFrame.size.height = labelSize.height
titleLabelFrame.origin.x = (self.frame.size.width / 2) - (labelSize.width / 2)
titleLabelFrame.origin.y = fitBoxRect.origin.y + imageFrame.size.height + kTextTopPadding
self.titleLabel!.frame = titleLabelFrame
self.titleLabel!.textAlignment = .center
}
}
It's working fine. 一切正常。 My problem is when I start using in UIStackView
. 我的问题是当我开始在UIStackView
使用时。 I am creating something similar to UITabBar
so I have 5 buttons next to each other. 我正在创建类似于UITabBar
东西,所以我彼此之间有5个按钮。 I want to middle button be in exact center of screen but it's always several pixels to side. 我希望中间按钮位于屏幕的确切中心,但侧面总是有几个像素。 I check my constraints for UIStackView
and it's okay. 我检查了我对UIStackView
约束,没关系。 I remove all buttons exect middle one and then it's in exact middle. 我删除了所有按钮,它们正中间,然后正好位于中间。 I tried different options for UIStackView
(Fill, Centered, Fill Equally, etc.). 我为UIStackView
尝试了其他选项(填充,居中, UIStackView
填充等)。 Nothing helps. 没有任何帮助。 Do anyone has any idea? 有人知道吗? Each button has different icon (with different size) and texts are different too (free, premium, etc. - sometimes bigger then icon sometimes smaller), is this relevant? 每个按钮都有不同的图标(大小不同),文本也不同(免费,高级等-有时更大,然后有时更小),这相关吗?
Example of my StackView (red line shows where is middle): 我的StackView的示例(红线显示中间位置):
The image size is going to be relevant here. 图像大小在这里将是相关的。 Once you get all 5 images to be the same exact size you won't experience this issue anymore. 一旦获得所有5张图像的大小完全相同,您就不会再遇到此问题。 Using 'fill equally' after doing that and you will get the result you want 使用“平均填充”后,您将获得想要的结果
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.