我正在尝试创建一个在图标下方有一些文本的按钮(类似于应用程序按钮),但它似乎很难实现。任何想法我怎样才能让文本显示在图像 下方UIButton?
UIButton
或者你可以只使用这个类别:
@interface UIButton (VerticalLayout) - (void)centerVerticallyWithPadding:(float)padding; - (void)centerVertically; @end @implementation UIButton (VerticalLayout) - (void)centerVerticallyWithPadding:(float)padding { CGSize imageSize = self.imageView.frame.size; CGSize titleSize = self.titleLabel.frame.size; CGFloat totalHeight = (imageSize.height + titleSize.height + padding); self.imageEdgeInsets = UIEdgeInsetsMake(- (totalHeight - imageSize.height), 0.0f, 0.0f, - titleSize.width); self.titleEdgeInsets = UIEdgeInsetsMake(0.0f, - imageSize.width, - (totalHeight - titleSize.height), 0.0f); self.contentEdgeInsets = UIEdgeInsetsMake(0.0f, 0.0f, titleSize.height, 0.0f); } - (void)centerVertically { const CGFloat kDefaultPadding = 6.0f; [self centerVerticallyWithPadding:kDefaultPadding]; } @end
extension UIButton { func centerVertically(padding: CGFloat = 6.0) { guard let imageViewSize = self.imageView?.frame.size, let titleLabelSize = self.titleLabel?.frame.size else { return } let totalHeight = imageViewSize.height + titleLabelSize.height + padding self.imageEdgeInsets = UIEdgeInsets( top: -(totalHeight - imageViewSize.height), left: 0.0, bottom: 0.0, right: -titleLabelSize.width ) self.titleEdgeInsets = UIEdgeInsets( top: 0.0, left: -imageViewSize.width, bottom: -(totalHeight - titleLabelSize.height), right: 0.0 ) self.contentEdgeInsets = UIEdgeInsets( top: 0.0, left: 0.0, bottom: titleLabelSize.height, right: 0.0 ) } }
建议: 如果按钮高度小于totalHeight,则图像将绘制外边框。
totalHeight
imageEdgeInset.top应该:
imageEdgeInset.top
max(0, -(totalHeight - imageViewSize.height))